如何在SwiftUI中停止Animation().repeatForever [英] How to STOP Animation().repeatForever in SwiftUI
问题描述
在SwiftUI中,我尝试使用按钮启动和停止动画.我无法在SwiftUI中找到让我停止自动化的方法.在Swift 4中,我曾经说过"startButton.layer.removeAllAnimations()". SwiftUI中有等效的东西吗?
In SwiftUI I am trying to start and STOP an animation with a button. I can't find a method within SwiftUI that lets me stop an automation. In Swift 4 I used to say "startButton.layer.removeAllAnimations()". Is there an equivalent in SwiftUI?
对于下面的代码,我将如何使用start的值来启用/禁用动画.我没有运气就尝试了.animation(start?Animation(...):.none)[在按钮内创建了一些奇怪的动画].
For the code below, how would I used the value of start to enable/disable the animation. I tried .animation(start ? Animation(...) : .none) without any luck [creates some odd animation within the button].
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()
}
}
推荐答案
以下操作应该可行,将动画移动到仅覆盖并添加条件到.default
(已通过Xcode 11.2/iOS 13.2测试)
The following should work, moved animation into overlay-only and added conditional to .default
(tested with 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中停止Animation().repeatForever的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!