To my knowledge there is not-yet a direct way to do a sequence of animations. This is more of a workaround than an actual solution, But it works, and its not too complicated.
Assuming you have a variable @State var animatedVariable
, when you want to apply animation to UI changing with the changes of your animatedVariable, you can say withAnimation { animatedVariable = someNewValue }
.
now if you want to do another animation after the first one completes, you should declare a new variable first: @State var delayedAnimatedVariable
and you can use it anywhere you want that delayed animation to be applied. to make it work, you better not set the value of delayedAnimatedVariable
directly. instead, you should listen to changes of animatedVariable
and change the value of delayedAnimatedVariable
with a delayed animation. for that, you should use .onChange
(available Xcode 12+) modifier:
.onChange(of: animatedVariable) { newValueOfAnimatedVariable in
withAnimation(Animation.default.delay(0.25)) {
delayedAnimatedVariable = newValueOfAnimatedVariable
}
}
EXAMPLE:
struct AnimatedView: View {
@State var animatedVariable = ""
@State var delayedAnimatedVariable = ""
var body: View {
VStack {
Button("Animated with delay!") {
withAnimation {
animatedVariable = "someNewValue"
}
}
// everything that uses `delayedAnimatedVariable` will have a delayed animation
// Note there is nothing to be animated in this example!
}
.onChange(of: animatedVariable) { newValue in
withAnimation(Animation.default.delay(0.25)) {
delayedAnimatedVariable = newValue
}
}
}
}
Question: why in withAnimation(Animation.default.delay(0.25))
you use 0.25
instead of anythings else like 0.5
or 0.3
or whatever?!
Answer: SwiftUI animations usually default to 0.25 seconds of duration, so if you apply the second animation with a 0.25 s delay, it will happen right after the first one. you can of course change that value based on your needs (you also can define duration of your animations, just as a PS, if you didnt know).