Previously we have seen the animation effect starts on clicking a button using the SwiftUI animation() modifier. But there may be situations where you may need to perform the animation instantly when the view appears. So in this tutorial, I am focusing on how to start an animation immediately after a view appears in SwiftUI.
In order to animate a view as soon as it appears on the screen, we have to use the onAppear()
modifier. Using this modifier, you will be able to attach the animation you want.
Below is a given example of using the onAppear()
modifier to start the animated scale effect immediately:
@State var scale = 1.0
var body: some View {
Text("Animated Text")
.scaleEffect(scale)
.onAppear {
withAnimation(.easeInOut(duration: 2)) {
scale = 3
}
}
}
Here we have used the withAnimation()
function inside the onAppear()
modifier to return the result of recomputing the body of the view with the provided animation.
And here is the screenshot of the animated effect that was captured by running the above code on the iPhone emulator of Xcode:
Now let’s see another example where the animation repeats forever. Here it is with repeat animation:
@State var scale = 1.0
var body: some View {
Text("Animated Text")
.scaleEffect(scale)
.onAppear {
withAnimation(.easeInOut(duration: 1).repeatForever(autoreverses: true) ) {
scale = 3
}
}
}
This time, the snippet will create the same animation with a different duration time and also repeat again and again using the repeatForever()
modifier.
In this example, the animation duration is 1 second. After completing the 1 second of animation, it auto reverses and starts again.