swift - 为什么在 SwiftUI 中的动画过程中动画不使用 View 的主体更新自身?
问题描述
我在向下代码中使用非常简单的示例上下移动一个圆圈,我们可以为这项工作启用或禁用动画!问题就在这里,当我想在过程中间移动带有动画的圆圈时,我想取消并杀死动画,但动画不尊重状态的变化!!!为什么会这样?在动画发生时,如何使动画符合并尊重状态值!?
struct ContentView: View {
@State private var alignmentBool: Bool = Bool()
@State private var activeAnimation: Bool = Bool()
var body: some View {
ZStack {
Color.gray.overlay(Circle().frame(width: 100, height: 100, alignment: .center), alignment: alignmentBool ? .top : .bottom)
.animation(!activeAnimation ? Animation.easeInOut(duration: 5) : nil, value: [alignmentBool, activeAnimation])
HStack {
Button("Move it!") { alignmentBool.toggle() }
Spacer()
Button("active/inactive Animation") { activeAnimation.toggle() }
}
.foregroundColor(Color.yellow)
.font(Font.body.bold())
.padding()
}
}
}
解决方案
没有明确的动画取消,但我们可以破坏动画视图以获得所需的效果:
Color.gray.overlay(Circle().frame(width: 100, height: 100, alignment: .center), alignment: alignmentBool ? .top : .bottom)
.animation(!activeAnimation ? Animation.easeInOut(duration: 5) : nil, value: [alignmentBool, activeAnimation])
.id(activeAnimation) // << here !!
使用 Xcode 13b / iOS 15 测试
推荐阅读
- java - java中使用栈的排序算法
- angular - angular 5中如何使用父组件的css到子组件
- javascript - javascript - better search value script in nested arrays
- rest - 使用 REST Post 功能将证书导入 IBM-Cloud 上的证书管理器(测试版)
- shell - 在 CMake 中配置运行脚本
- c++ - 程序在没有来自操作系统的信号的情况下挂在函数中的特定行
- java - 在关闭应用程序 javafx 时什么也不做
- javascript - expect.toBeDefined() 不是带有 expect.toMatchObject() 的函数
- mysql - 求和查询花费太多时间
- active-directory - 防止 ldapsearch 等实用程序锁定帐户