2
votes

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)
  }
1

1 Answers

1
votes

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 !!