简体   繁体   English

在 Swift UI 中停止旋转动画

[英]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.我希望不断旋转 Swift UI 视图,直到用户按下按钮,此时它会停止,直到再次按下它。 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.我尝试了一些变体,例如让“go”变量在 false 时将动画样式更改为 .none,或者让它更改旋转次数。 I know there are clunky solutions to this, such as using CBAnimation (like this answer) or a timer (like this answer) .我知道有一些笨拙的解决方案,例如使用 CBAnimation (像这个答案)或计时器(像这个答案) 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.如果可以的话,我希望避免这些解决方案——我很好奇是否有办法使用我无法弄清楚的 SwiftUI 动画来实现这一点。

Any help is much appreciated!任何帮助深表感谢!

You need to reset animation to default, like below您需要将动画重置为默认值,如下所示

演示

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

Tested with Xcode 12 / iOS 14使用 Xcode 12 / iOS 14 测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM