SwiftUIでアニメーションするときに animation(_:value:) を使いますが、ビューの表示・非表示を表現するときにモディファイアをつける位置に若干つまずいたのでメモしておきます。
こんなアニメーションを実装します。
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でもアニメーションしました。
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)
}
}