首页 > 解决方案 > 为什么在 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()
            
        }
        
    }
    
}

标签: swiftswiftui

解决方案


没有明确的动画取消,但我们可以破坏动画视图以获得所需的效果:

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 测试


推荐阅读