LoginSignup
17
7

More than 1 year has passed since last update.

SwiftUI の画面遷移アニメーションを無効にする

Last updated at Posted at 2022-05-21

SwiftUI で画面遷移を行うための方法に .sheet.fullScreenCoverNavigationLink などがありますが、いずれもデフォルトでアニメーションがついています。このアニメーションはほとんどの場合にはありがたいですが、ときには邪魔になることがあります。

disablesAnimationtrue にした Transaction の中で画面遷移を発生させることでアニメーションなしで遷移させることができます。

var transaction = Transaction()
transaction.disablesAnimations = true
withTransaction(transaction) {
    // ここで画面遷移を発生させる
}

具体例として、 .fullScreenCover のアニメーションを無効にしたものを示します。 .sheetNavigationLink にも同様の方法が使えます。

struct ContentView: View {
    @State private var isPresented: Bool = false
    
    var body: some View {
        VStack {
            Button(action: {
                // NOTE: ここで表示アニメーションを無効にしている
                var transaction = Transaction()
                transaction.disablesAnimations = true
                withTransaction(transaction) {
                    isPresented = true
                }
            }) {
                Text("FullScreenCover")
            }
        }
        .fullScreenCover(isPresented: $isPresented) {
            FullScreenView()
        }
    }
}

struct FullScreenView: View {
    @Environment(\.dismiss) var dismiss
    
    var body: some View {
        ZStack {
            Color.black.ignoresSafeArea()
            
            Button(action: {
                // NOTE: ここで非表示アニメーションを無効にしている
                var transaction = Transaction()
                transaction.disablesAnimations = true
                withTransaction(transaction) {
                    dismiss()
                }
            }) {
                Text("Close")
                    .foregroundColor(.white)
            }
        }
    }
}
通常の .fullScreenCover ^ のコードでアニメーションを無効にしたもの
before.gif after.gif

以上です。

この記事は Transaction の機能のうちの一部しか使っていません。Transaction の基礎知識や一般的な使い方については以下の記事がわかりやすいと思います。

17
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
7