如何让不同的组件有不同的动画?



我有两个简单的ui组件:矩形和图像。我只需要矩形的幻灯片动画和图像的缩放动画。

然而,我得到了一个默认值的动画这两个。我的代码有问题吗?没有任何错误。我用的是beta SF Symbols。这就是问题所在吗?

import SwiftUI
struct ContentView: View {
@State var animate: Bool = false
var body: some View {
VStack(alignment: .center) {
HStack() {
if animate {

ZStack() {
Rectangle()
.frame(height: 50)
.transition(.slide)
Image(systemName: "figure.mixed.cardio")
.foregroundColor(.white)
.transition(.scale)
}

}
}
Button("animate") {
withAnimation {
animate.toggle()
}
}
}
}
} 

Transition在特定视图出现时工作,但是在你的代码中ZStack加载视图,然后作为一个整体出现。

HStack() {
ZStack() {
if animate {   // << here !!

Rectangle()
.frame(height: 50)
.transition(.slide)
Image(systemName: "figure.mixed.cardio")
.foregroundColor(.white)
.transition(.scale)
}

}
}

这里的问题既不是你的SF符号也不是编译错误。动画有点棘手,特别是如果你想在同一个堆栈中为不同的视图提供不同的动画。

为了实现你的目标,你需要将每个子视图包装在一个独立的堆栈中,然后它们将有自己独特的动画。

试试这个代码:

import SwiftUI
struct TestView: View {
@State var animate: Bool = false
var body: some View {
VStack(alignment: .center) {
HStack() {
ZStack() {
//added
if animate {
ZStack {
Rectangle()
.frame(height: 50)

}   .transition(.slide)
}
//added
if animate {
ZStack {
Image(systemName: "figure.mixed.cardio")
.foregroundColor(.white)

}.transition(.scale)
}
}
}
Button("animate") {
withAnimation {
animate.toggle()
}
}
}
}
}

最新更新