Learn Courses My Dashboard

Animation control, button changes variable but not really

CleanShot 2022-12-03 at 22.51.13

I’d love any help understanding why the buttons change the variable but don’t actually change the speed of the animation.

struct _2animation: View {
    
    @State private var isRotating = true
    @State private var speed0 = 5.5

    var body: some View {
        VStack {
            Spacer()
            Image("Layer0")
                .resizable()
                .frame(width: 200, height: 200)
                .rotationEffect(.degrees(isRotating ? 360 : 0))
                .animation(.linear(duration: speed0).repeatForever(autoreverses: false), value: isRotating)
            Spacer()
            // not sure why these buttons don't do anything
            HStack {
                Button("fast") {
                    speed0 = 2.0
                }
                Button("slow") {
                    speed0 = 10.0
                }
            }
            Spacer()
            Text("\(speed0)")
            Spacer()
        }
        .onAppear {
            isRotating = false
        }
    }
}

Animation puzzles me at times too.

This works but I don’t really understand why yours did not.

For whatever the reason, you have to Stop the animation and then choose the speed you want which starts the animation again.

struct _2animation: View {

    @State private var isRotating = false
    @State private var speed0 = 5.5
    var animationStyle: Animation {
        Animation.linear(duration: speed0).repeatForever(autoreverses: false)
    }

    var body: some View {
        VStack {
            Spacer()
            Image(systemName: "globe")
                .resizable()
                .frame(width: 200, height: 200)
                .rotationEffect(.degrees(isRotating ? 360 : 0))
                .animation(isRotating ? animationStyle : .default, value: isRotating)
            Spacer()
            // not sure why these buttons don't do anything
            HStack {

                Button("fast") {
                    speed0 = 2.0
                    isRotating = true

                }
                Button("slow") {
                    speed0 = 10.0
                    isRotating = true
                }

                Button("Stop") {
                    isRotating = false
                }
            }
            Spacer()
            Text("\(speed0)")
            Spacer()
        }
       
    }
}