How To Change Animation Duration And Delay In SwiftUI

The duration and delay are important when you need to synchronize view animations and you want to be sure that all of them make an awesome effect and it’s easy to change it.

Changing duration is useful especially when you need to test fast animation and you’re not sure if it works as you want.

Let’s say you have Infinity animation from this post.

@State private var width: CGFloat = 100
@
State private var color = Color.red

var body: some View {
    
Rectangle()
    
    .frame(width: width, height: 100)
    
    .foregroundColor(color)
    
    .onAppear(perform: {
    
        withAnimation(Animation.easeIn.repeatForever()) {
    
            width = 10
    
            color = .blue
    
        }
    
    })
}

Now you want to slow it down because it’s too fast, there is a parameter in creating animation called duration, Animation.easeIn(duration: 2)

withAnimation(Animation.easeIn(duration: 2).repeatForever()) {
    
width = 10
    
color = .blue
}

Animation now takes 2 seconds, it’s Double value so you can put there 2.5 for example if you don’t want to round it to whole numbers.

To delay animation there is .delay that can be used on Animation instance.

.delay(0.5)

withAnimation(Animation.easeIn(duration: 2).delay(0.5).repeatForever()) {
    
width = 10
    
color = .blue
}