In this tutorial, you are going to learn how we can delay animation by a specific amount of time in SwiftUI. There is nothing complicated in achieving this task. After completing this tutorial, it is going to be just a piece of cake for you to delay any animation done by using the animation() modifier.
For example, if you set an animation effect to a view and you want the animation to be started after 3 seconds then you have to delay it by 3 seconds.
In SwiftUI, we can perform this task by using the delay()
modifier within the SwiftUI animation()
modifier. All its needs to provide is the delay time in seconds as the parameter to the modifier.
Below is how we have to use the delay modifier:
...
.animation(.easeIn.delay(2), value: animationValue)
Well, you can also use it even if you set the duration for the animation:
...
.animation(.easeIn(duration: 1).delay(2), value: animationValue)
Let’s see a working example where we apply an animation with a rotation effect and the animation will start by delaying 2 seconds:
@State private var rotateAngle = 0.0
var body: some View {
Button("Press to rotate") {
rotateAngle += 60
}
.rotationEffect(.degrees(rotateAngle))
.animation(.easeIn(duration: 1).delay(2), value: rotateAngle)
}
In the above example, we are rotating a button at 60 degrees of angle with an animation effect.
If a user taps the button, the animation starts after delaying by 2 seconds as we have set delay(2)
in the animation modifier.
That’s it… So simple? isn’t it…
I hope you have understood how to use the delay() modifier in SwiftUI to start an animation with a delay by providing a specific amount of time.