Search code examples
animationswiftui

SwiftUI animation (animation(_:value:): Newbie question


I am learning SwiftUI animation and I have a Newbie question. The .animation() modifier has been deprecated in iOS 15. For animation to work, 'value' has to change. With my changes to an example, the motion is jerky and not as smooth without 'value'. .animation() is deprecated but still works with a warning.

Am I doing it right?

Example from: https://medium.com/apple-developer-academy-federico-ii/drawings-and-animations-in-swiftui-3a2da460e492

struct Example4: View {
    @State private var bounceBall: Bool = false
    @State private var hiddenText: String = "Kick the ball!"
    var body: some View {
        VStack {
            Text(hiddenText)
            Image("ball")
                .resizable()
                .frame(width: 150, height: 150)
                .clipShape(Circle())
                // *Original* 
                .animation(Animation.interpolatingSpring(stiffness: 90, damping: 1.5).repeatForever(autoreverses: false))
                // *Modified*
                .animation(Animation.interpolatingSpring(stiffness: 90, damping: 1.5).repeatForever(autoreverses: false), value: bounceBall)
                .offset(y: bounceBall ? -200 : 200)
                .onTapGesture {
                    self.bounceBall.toggle()
                    self.hiddenText = ""
            }
        }
        .navigationBarTitle("Example 4")
    }
}

Solution

  • On my M1 MacBook Air, I had the jerky motion both ways, whether using the deprecated .animation() or the new .animation(value:), and yes, you're using the value: bounceBall correctly.

    I'm also relatively new to developing, nonetheless I want to throw out an alternative to .animation() that will get rid of the warning:

    Image("ball")
        .resizable()
        .frame(width: 150, height: 150)
        .clipShape(Circle())
        .offset(y: bounceBall ? -200 : 200)
        .onTapGesture {
            withAnimation(
                Animation.interpolatingSpring(stiffness: 90, damping: 1.5).repeatForever(autoreverses: false)
            ) {
                bounceBall.toggle()
                hiddenText = ""
            }
        }