sup*_*cio 5 user-interface animation ios swift swiftui
根据 Apple 文档,我们应该能够将动画直接附加到过渡。例如:
.transition(AnyTransition.slide.animation(.linear))
Run Code Online (Sandbox Code Playgroud)
该方法的文档:
extension AnyTransition {
/// Attach an animation to this transition.
public func animation(_ animation: Animation?) -> AnyTransition
}
Run Code Online (Sandbox Code Playgroud)
说:
概括
为该过渡添加动画。
但我无法让它发挥作用。看一下这个最小可行的示例(您可以复制粘贴它并自己尝试):
import SwiftUI
struct AnimationTest: View {
@State private var show = false
var body: some View {
VStack {
if show {
Color.green
.transition(AnyTransition.slide.animation(.linear))
} else {
Color.yellow
.transition(AnyTransition.slide.animation(.linear))
}
Button(action: {
self.show.toggle()
}, label: {
Text("CHANGE VIEW!")
})
}
}
}
struct AnimationTest_Previews: PreviewProvider {
static var previews: some View {
AnimationTest()
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,根本没有动画发生。有任何想法吗?谢谢。
您需要将布尔切换包装在withAnimation()
闭包中:
withAnimation {
self.show.toggle()
}
Run Code Online (Sandbox Code Playgroud)
在模拟器上测试了 Xcode 11.2.1 上的转换工作;画布不会预览它。
请注意,直接应用于视图的动画/过渡会对该特定视图及其子视图产生影响。此外,根据文档:
func animation(Animation?) -> View
Run Code Online (Sandbox Code Playgroud)
将给定的动画应用于视图中的所有可设置动画的值。
由于可动画化的值(在本例中是启用转换的布尔切换)位于颜色视图的外部,因此必须从按钮操作中设置的位置显式对其进行动画化。另一种方法是,可以有效地将过渡直接附加到目标视图,但将动画应用到其容器,从而能够对show
. 所以,这也达到了想要的结果:
struct AnimationTest: View {
@State private var show = false
var body: some View {
VStack {
if show {
Color.green
.transition(.slide)
} else {
Color.yellow
.transition(.slide)
}
Button(action: {
self.show.toggle()
}, label: {
Text("CHANGE VIEW!")
})
}
.animation(.linear)
}
}
Run Code Online (Sandbox Code Playgroud)