You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI视图缩放动画结束后如何恢复至初始状态?

解决SwiftUI动画结束后不返回初始状态的问题

要让脉冲动画完成4次后回到1倍缩放的初始状态,你可以用以下两种实用方案:

方案1:利用动画完成回调重置状态(iOS 15+)

通过withAnimation的completion闭包,在整个动画序列结束后手动将缩放值重置为初始值。这种方式逻辑直观,适合需要明确处理动画收尾的场景。

修改后的代码:

struct ContentView: View {
    @State private var scale: Double = 1
    
    var body: some View {
        Rectangle()
            .fill(.red)
            .frame(width: 200, height: 200)
            .scaleEffect(scale)
            .onAppear {
                withAnimation(Animation.easeInOut(duration: 1)
                    .repeatCount(4, autoreverses: true)
                    .delay(1)) {
                        scale = 1.2
                    } completion: {
                        // 动画全部结束后重置回初始缩放
                        scale = 1
                    }
            }
    }
}

方案2:用临时触发变量控制动画(兼容低版本)

不直接修改scale的最终状态,而是用一个布尔变量作为动画触发开关,让缩放值随开关状态动态变化,动画结束后关闭开关即可回到初始状态。这种方式更贴合SwiftUI的状态驱动设计。

修改后的代码:

struct ContentView: View {
    @State private var startAnimation = false
    
    var body: some View {
        Rectangle()
            .fill(.red)
            .frame(width: 200, height: 200)
            .scaleEffect(startAnimation ? 1.2 : 1)
            .animation(Animation.easeInOut(duration: 1)
                .repeatCount(4, autoreverses: true)
                .delay(1), value: startAnimation)
            .onAppear {
                startAnimation = true
                // 计算动画总时长:初始延迟1s + 4次来回(每次2s)= 9s
                DispatchQueue.main.asyncAfter(deadline: .now() + 9) {
                    startAnimation = false
                }
            }
    }
}

补充说明

  • 方案1的completion是iOS 15及以上才支持的API,如果你的项目需要兼容iOS 14或更早版本,优先选方案2。
  • 方案2中的延迟时间计算:delay(1)是初始等待时间,每次完整的缩放+反转动画时长是2秒(1秒放大+1秒缩小),4次重复就是8秒,总时长1+8=9秒,确保动画完全结束后再重置触发变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:32:15