【问题标题】:How to STOP Animation().repeatForever in SwiftUI如何在 SwiftUI 中停止 Animation().repeatForever
【发布时间】:2020-01-20 17:55:37
【问题描述】:

在 SwiftUI 中,我尝试使用按钮启动和停止动画。我在 SwiftUI 中找不到让我停止自动化的方法。在 Swift 4 中,我曾经说过“startButton.layer.removeAllAnimations()”。 SwiftUI 中是否有等价物?

对于下面的代码,我将如何使用 start 的值来启用/禁用动画。我试过 .animation(start ? Animation(...) : .none) 没有任何运气[在按钮内创建了一些奇怪的动画]。

import SwiftUI

struct Repeating_WithDelay: View {
    @State private var start = false

    var body: some View {
        VStack(spacing: 20) {
            TitleText("Repeating")
            SubtitleText("Repeat With Delay")
            BannerText("You can add a delay between each repeat of the animation. You want to add the delay modifier BEFORE the repeat modifier.", backColor: .green)

            Spacer()

            Button("Start", action: { self.start.toggle() })
                .font(.largeTitle)
                .padding()
                .foregroundColor(.white)
                .background(RoundedRectangle(cornerRadius: 10).fill(Color.green))
                .overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(Color.green, lineWidth: 4)
                        .scaleEffect(start ? 2 : 0.9)
                        .opacity(start ? 0 : 1))
                .animation(Animation.easeOut(duration: 0.6)
                    .delay(1) // Add 1 second between animations
                    .repeatForever(autoreverses: false))

            Spacer()

        }
        .font(.title)
    }
}

struct Repeating_WithDelay_Previews: PreviewProvider {
    static var previews: some View {
        Repeating_WithDelay()
    }
}

【问题讨论】:

    标签: animation swiftui


    【解决方案1】:

    以下应该可以工作,将动画移动到仅覆盖并添加条件到.default(使用 Xcode 11.2 / iOS 13.2 测试)

    Button("Start", action: { self.start.toggle() })
        .font(.largeTitle)
        .padding()
        .foregroundColor(.white)
        .background(RoundedRectangle(cornerRadius: 10).fill(Color.green))
        .overlay(
            RoundedRectangle(cornerRadius: 10)
                .stroke(Color.green, lineWidth: 4)
                .scaleEffect(start ? 2 : 0.9)
                .opacity(start ? 0 : 1)
                .animation(start ? Animation.easeOut(duration: 0.6)
                    .delay(1) // Add 1 second between animations
                    .repeatForever(autoreverses: false) : .default)
        )
    

    【讨论】:

    • 谢谢。有时最简单的事情会被如此忽视。
    • 向叠加层添加动画有助于修复 SwiftUI 的奇怪行为
    • 我刚刚通过了解如何使用 .default 三元替代方案节省了数小时或更长时间。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多