Chris McElroy
Chris McElroy

Reputation: 521

Stopping rotation animations in Swift UI

I am hoping to rotate a Swift UI view continuously until a user presses a button, at which point it stops until it is pressed again. From a few sources like this one, I thought that this code would work:

struct ContentView: View {
    @State var go = false
    let style = Animation.linear.repeatForever(autoreverses: false)

    var body: some View {
        VStack {
            Button("Rotate") {
                go.toggle()
            }
            Text("wheee")
                .rotationEffect(.degrees(go ? 360 : 0))
                .animation(style)
        }
    }
}

I expect the “Rotate” button to start and stop the rotation. It starts fine, but it won’t stop—the view starts twitching back and forth instead, only becoming worse the more you press the button.

I have tried a few variations, such as having the “go” variable change the animation style to .none when false, or having it change the number of rotations. I know there are clunky solutions to this, such as using CBAnimation (like this answer) or a timer (like this answer). I am hoping to avoid these solutions if I can—I’m curious if there is a way to implement this using SwiftUI animations that I haven’t been able to figure out.

Any help is much appreciated!

Upvotes: 2

Views: 1532

Answers (1)

Asperi
Asperi

Reputation: 258413

You need to reset animation to default, like below

demo

Text("wheee")
    .rotationEffect(.degrees(go ? 360 : 0))
    .animation(go ? style : .default)        // << here !!

Tested with Xcode 12 / iOS 14

Upvotes: 3

Related Questions