You need to enable JavaScript to run this app. SwiftUI中如何让正在运行的动画在当前状态停止
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何让正在运行的动画在当前状态停止

问题原因

你现有的写法问题在于withAnimation仅会在视图首次加载触发onAppear时执行一次,后续修改enabled状态并不会重新触发这段逻辑,自然无法中断已经运行的动画。

修正方案

核心思路是点击时先获取动画执行到当前时刻的实时偏移量,把这个值赋值给offset覆盖原本的动画终点,直接打断原有动画链路,就能实现停在当前位置的效果。

struct ContentView: View {
    @State private var offset = 0.0
    @State private var animationEnabled = true
    
    var body: some View {
        Circle()
            .frame(width: 100, height: 100)
            .foregroundColor(.blue)
            .offset(y: offset)
            // 将动画绑定到offset变化,动画开关状态变更时自动生效
            .animation(animationEnabled ? .easeIn(duration: 5) : nil, value: offset)
            .onAppear {
                offset = Double(-UIScreen.main.bounds.size.height + 300)
            }
            .onTapGesture {
                // 捕获当前动画进程中的实时偏移量
                let currentOffset = self.presentationValue?.offset.y ?? offset
                // 覆盖offset值,中断原有动画
                offset = currentOffset
                animationEnabled = false
            }
    }
}

// 扩展View方便取当前动画中的展示值
extension View {
    var presentationValue: Self {
        Mirror(reflecting: self)
            .children
            .first { $0.label == "presentationValue" }?
            .value as? Self ?? self
    }
}

内容的提问来源于stack exchange,提问作者Viks Viks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 17:36:04