'SwiftUI animation with repeat count ends without animation
I have a rotate effect animation that I want to end at a specific number of repeats. the problem I have is that the animation ends without animation and very suddenly. and also in the wrong orientation.
Image(systemName: "iphone")
.imageScale(.large)
.font(.custom("Masive", size: 60))
.rotationEffect(.degrees(0))
.rotationEffect(Angle(degrees: isAnimating ? -90 : 0))
.frame(width: 60, height: 80, alignment: .center)
.accessibilityLabel("A phone is repeatedly rotating and back")
Here is the withAnimation that I used on ZStack wrapped the Image.
.onAppear {
withAnimation(Animation.spring().delay(1).repeatCount(2)) {
isAnimating.toggle()
}
}
Solution 1:[1]
TL;DR
To fix sudden animation end, you should increase the argument inside .repeatCount to 3.
withAnimation(Animation.spring().delay(1).repeatCount(3)) {
isAnimating.toggle()
}
Why does this happen?
This "bug" happens because when the isAnimating equals true, your image is rotated to -90 degrees. But the animation values go like:
(arrow means animation cycle)
0 -> -90 -> 0
So when the animation is ended, SwiftUI still need this view to be rotated, so it does it without any animation. So, we need to use odd values inside .repeatCount()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | alexandrov |

