7
5

SwiftUIでビューの表示・非表示をアニメーションする

Posted at

SwiftUIでアニメーションするときに animation(_:value:) を使いますが、ビューの表示・非表示を表現するときにモディファイアをつける位置に若干つまずいたのでメモしておきます。

こんなアニメーションを実装します。

animation.gif

struct ContentView: View {
    @State var condition = true

    var body: some View {
        VStack {
            Button("Button") {
                condition.toggle()
            }

            ZStack {
                if condition {
                    Text("Hello")
                } else {
                    Text("World")
                }
            }
            .animation(.easeOut(duration: 1.0), value: condition)
        }
        .frame(width: 300, height: 300)
    }
}

アニメーションしたいのはTextビューですが、animation(_:value:)はコンテナビューに対してつけます。

ZStack {
    if condition {
        Text("Hello")
    } else {
        Text("World")
    }
}
.animation(.easeOut(duration: 1.0), value: condition)

条件によって表示するビューを切り替えるときにコンテナとしてGroupを使うことがあると思いますが、Groupに対してanimation(_:value:)をつけてもアニメーションしないので要注意です。

// Groupだとアニメーションしない
Group {
    if condition {
        Text("Hello")
    } else {
        Text("World")
    }
}
.animation(.easeOut(duration: 1.0), value: condition)

おまけですが、条件にマッチしたときだけビューを表示する例です。
ちなみにoverlay内だとGroupでもアニメーションしました。

animation.gif

struct ContentView: View {
    @State var condition = false

    var body: some View {
        VStack {
            Button("Button") {
                condition.toggle()
            }

            RoundedRectangle(cornerRadius: 4)
                .foregroundStyle(Color.clear)
                .frame(width: 100, height: 50)
                .overlay(Color.gray, in: RoundedRectangle(cornerRadius: 4).stroke(lineWidth: 1))
                .overlay {
                    ZStack {
                        if condition {
                            Text("Hello")
                        }
                    }
                    .animation(.easeOut(duration: 1.0), value: condition)
                }
        }
        .frame(width: 300, height: 300)
    }
}
7
5
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
7
5