swift - SwiftUI 中的条件动画停止工作
问题描述
我有这个代码:
Group{
if self.done{
Image(systemName: "plus").font(.system(size: 40)).foregroundColor(.gray)
.padding().overlay(Circle().stroke(Color.gray, lineWidth: 3)).opacity(0.6)
}
else{
Button(action: {self.showSearchTrash = 1}){
Image(systemName: "plus").font(.system(size: 40)).foregroundColor(green)
.padding().overlay(Circle().stroke(green, lineWidth: 3).scaleEffect(1+self.animationAmount).animation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: true)).onAppear {self.animationAmount = 0.1})
}
}
}.padding(.bottom, 5)
意图是如果self.done
是false
,加号按钮上的圆圈将无限期地扩大和收缩。
这行得通。但是,如果我使用切换设置self.done
为true
,然后将其转回false
,则不再出现动画。我知道问题不在于切换开关,因为它确实恢复为绿色。
另外,缺少.
beforegreen
是故意的——我定义了一个特定的 Color green
。
知道为什么动画停止工作/如何解决这个问题吗?
解决方案
您可以Animation
在withAnimation
块中指定并创建单独的函数来启动/停止动画。
这是一个可能的解决方案:
struct ContentView: View {
@State private var done = false
@State private var animationAmount: CGFloat = 0
var body: some View {
VStack {
Toggle("Done", isOn: $done)
plusImage
.opacity(done ? 0.6 : 1)
.foregroundColor(done ? .gray : .green)
}
.onAppear(perform: startAnimation)
.onChange(of: done) { done in
if done {
stopAnimation()
} else {
startAnimation()
}
}
}
var plusImage: some View {
Image(systemName: "plus")
.font(.system(size: 40))
.padding()
.overlay(
Circle()
.stroke(Color.gray, lineWidth: 3)
.scaleEffect(1 + animationAmount)
)
}
}
private extension ContentView {
func startAnimation() {
withAnimation(Animation.easeInOut(duration: 1).repeatForever()) {
animationAmount = 0.1
}
}
func stopAnimation() {
withAnimation {
animationAmount = 0
}
}
}
推荐阅读
- python - 烧瓶登录中基于角色的授权
- verilog - 如何在 Synopsys Verdi 中使用 Find Scope
- c++ - 在 C++ 中使用初始化列表填充多维结构数组的问题
- opengl - 在 OpenGL glTexImage2D() 中,如果“数据”指针为 NULL,最后两个枚举是否执行任何操作?
- pine-script - 结合STOCH RSI和Macd进行策略
- web-config - 最有效的 web.config 重定向
- javascript - 将函数参数传递给另一个函数
- mongodb - 为什么在聚合函数中使用 $project 时重命名 mongodb 中对象的子数组中的字段返回数组?
- windows - 为什么某些软件(如 chrome)会在 Windows 10 中显示奇怪的故障文本?
- azure - 过滤数据并使用 Azure 数据工厂将其加载到相应的表中