Looping and Delaying Animations in SwiftUI: Using Repeat, RepeatForever, Speed, and Delay

Animation Repeat, Delay and Speed : How to customize your Animation timing with the repeatCount, repeatForever, speed and delay modifiers. This is a great technique for creating looping loading animation, sequencing multiple animations or creating a nice intro animation.

Looping Animation 
If you'd like the animation to keep going and never stop, you can add the the repeatForever modifier to it. Since we're using multiple modifiers such linear and repeatForever, the Animation type is required.

.animation(
	Animation.linear.repeatForever()
)
..
The animation timing is also required. Note that you can use other timings such easeOut, timingCurve and spring.
Animation.easeOut.repeatForever()
..
By adding the autoreverses parameter and setting its value to false, you're also ensuring that the animation doesn't reset but goes on continuously back and forth.
Animation.linear.repeatForever(autoreverses: false)
..
Repeat Count 
Using repeatCount, you can specify the number of times your animation can be repeated.
Animation.linear.repeatCount(3)
..
Delay Animation 
A great way to sequence animation is to use delay. The unit is in seconds.
Animation.linear.delay(0.5)
..
Animation Speed 
Speed is an Animation modifier that takes into consideration your current animation timing and multiply the speed. For example, 2 will make your overall animation twice as fast. 0.5 would make your animation twice as slow.
Animation.linear.speed(2)
..
Output:
This code creates a loading animation using a circle shape that is trimmed. The animation repeats infinitely by using the appear state.
struct ContentView: View {
    @State var appear = false

    var body: some View {
        Circle()
            .trim(from: 0.2, to: 1)
            .stroke(Color.blue, style: StrokeStyle(lineWidth: 5, lineCap: .round, lineJoin: .round))
            .frame(width: 44, height: 44)
            .rotationEffect(Angle(degrees: appear ? 360 : 0))
            .animation(Animation.linear(duration: 2).repeatForever(autoreverses: false))
            .onAppear {
                appear = true
            }
    }
}
..

Comments