Reputation: 43
i am trying to build my own loading indicator view. Therefore I have a black circle and there I place an image over it which needs to be rotated repeatedly.
This is my code:
public struct MyLoadingIndication: View {
private var rotateAnimation: Animation {
Animation.linear(duration: 2.0).repeatForever(autoreverses: false)
}
@State private var isAnimating = false
public var body: some View {
ZStack(alignment: .center) {
Color.black
.frame(width: 66, height: 66)
Image(systemName: "clock")
.resizable()
.scaledToFit()
.frame(width: 56, height: 56)
.rotationEffect(Angle(degrees: isAnimating ? 360 : -360))
.animation(rotateAnimation)
.foregroundColor(.yellow)
}
.onAppear {
isAnimating = true
}
}
}
Now i have the problem, when i initialise this view in another view the "yellow" clock rotates BUT also moves from bottom to top repeatedly.
Does anybody knows why this is happening?
EDIT:
It seams that this occurs when I add a navigation bar title display mode to the parent view:
MyLoadingIndication()
.navigationBarTitleDisplayMode(.inline)
Thanks in advance.
Upvotes: 1
Views: 535
Reputation: 43
I solved it by myself. I needed to change the .onAppear block:
.onAppear {
DispatchQueue.main.async {
withAnimation(animation) {
isAnimating = true
}
}
}
Now everything is working.
Upvotes: 2
Reputation: 2889
It appears that because your animation is not linked to any state variables, the animation of the clock gets interfered with the NavigationView's own layout animations (I might be wrong on the exact root cause though).
However, if you replace
.animation(rotateAnimation)
with
.animation(rotateAnimation, value: isAnimating)
it should work correctly because you'll have an explicit state variable affecting the animation.
Upvotes: 0