'SwiftUI hiding navigation bar affects other animations
I have the following SwiftUI view and I want to have it repeat the scale animation to simulate a pulsing effect.
However, in addition to the scaling, the circle is also moving up and down. It seems like the reason is because I set navigationBarHidden to true, which causes the circle to shift down and that shifting animation repeats together with the scaling animation. Removing the navigationBarHidden line would fix the issue but I would like to hide the navigation bar.
How can I make sure the repeat animation here only applies to the scalingEffect and make sure the animation doesn't get affected when hiding the navigation bar? Any help would be greatly appreciated!
@State var animate = false
var body: some View {
ZStack {
Circle()
.frame(width: 200, height: 200, alignment: .center)
.scaleEffect(animate ? 0.7 : 1.0, anchor: .center)
.animation(Animation.default.repeatForever(autoreverses: true))
}
.onAppear {
self.animate.toggle()
}
.navigationBarHidden(true)
}
Solution 1:[1]
Make animation per-value on state, like
Circle()
.frame(width: 200, height: 200, alignment: .center)
.scaleEffect(animate ? 0.7 : 1.0, anchor: .center)
.animation(Animation.default.repeatForever(autoreverses: true),
value: animate) // << here !!
Solution 2:[2]
I had the same issue as the whole view moving up and down when its child view is hidden and shown (animation) repeatedly.
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 | Asperi |
Solution 2 | Phan Hoang |