SwiftUI 同一元素的多个动画 [英] SwiftUI multiple animations for same element
问题描述
我是 SwiftUI 的新手,但我对 Storyboard 有很好的了解.
I'm new to SwiftUI, but I have a good knowledge about Storyboard.
一开始我想从一些动画开始,但其中一个有问题:
At the beginning I want to start with some animations, but I have a problem with one of them:
- 我想让一张图片从一开始的 0x0 变成 50x50 的大小.
- 在 50x50 之后,它应该重复一个动画,使大小为 50x50 ->40x40 ->50x50 ->...永远
我知道 @State
变量,.onAppear
事件,使用 autoreverse
bool 重复动画,但我不知道如何使用它们成为最佳分辨率.
I know @State
variables, the .onAppear
event, repeating animations with the autoreverse
bool, but I don't know how to use them to become the best resolution.
希望有人能帮助我.
@State var element_appeared : Bool = false
Image(systemName: "paperplane.fill")
.resizable()
.frame(width: element_appeared ? 50 : 0, height: element_appeared ? 50 : 0)
.onAppear() {
element_appeared.toggle()
}
.animation(.easeInOut)
这就是开头动画的工作方式.我认为我必须处理 element_appeared
变量,但我真的不知道如何..
This is how the animation at the beginning works. I think that I have to work on the element_appeared
variable, but I really don't know how..
推荐答案
你可以创建一个枚举,因为你的动画有两个以上的状态.然后使用DispatchQueue
来延迟第二个动画.
You can create an enum as you animation has more than two states. Then use DispatchQueue
to delay the second animation.
这是一个演示:
enum AnimationState {
case notAppeared, appeared, animating
}
struct ContentView: View {
@State private var animationState: AnimationState = .notAppeared
private let delay: TimeInterval = 1
var body: some View {
Image(systemName: "paperplane.fill")
.resizable()
.frame(width: imageSize, height: imageSize)
.onAppear {
withAnimation(.easeInOut(duration: delay)) {
animationState = .appeared
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
withAnimation(Animation.easeInOut.repeatForever()) {
animationState = .animating
}
}
}
}
private var imageSize: CGFloat {
switch animationState {
case .notAppeared: return 0
case .appeared: return 50
case .animating: return 40
}
}
}
这篇关于SwiftUI 同一元素的多个动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!