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

如何减慢Loading视图的动画速度?SwiftUI动画偶尔过快问题排查

问题分析与解决方案

你的Loading动画偶尔速度过快,核心问题出在**onDisappear中手动重置isAnimating为false**的操作:

  • 当视图消失时,强制将isAnimating设为false会让Circle瞬间跳转到0度的初始状态,而非让动画自然终止。
  • 若视图是被隐藏而非销毁(比如在TabView、NavigationView中切换),再次出现时重新启动动画会和残留的动画状态冲突,导致出现跳变或速度异常的情况。

修复后的代码

移除onDisappear中的状态重置,让SwiftUI自动管理动画的生命周期:

public struct CircleLoadingView: View {
    @State private var isAnimating = false
    
    public init() {
    }

    public var body: some View {
        Circle()
            .trim(from: 0, to: 0.25)
            .stroke(Color.s500, lineWidth: 4)
            .frame(width: 40, height: 40)
            .rotationEffect(Angle(degrees: isAnimating ? 360 : 0))
            .onAppear {
                withAnimation(Animation.linear(duration: 1).repeatForever(autoreverses: false)) {
                    isAnimating = true
                }
            }
            // 移除onDisappear的状态重置逻辑
    }
}

struct CircleProgressViewDemo: View {
    var body: some View {
        VStack(spacing: 20) {
            CircleLoadingView()
            Spacer()
        }
    }
}

可选优化方案

如果需要更稳定的动画控制,也可以直接绑定一个持续递增的旋转角度变量,避免依赖布尔值的状态切换:

public struct CircleLoadingView: View {
    @State private var rotation = 0.0
    
    public init() {
    }

    public var body: some View {
        Circle()
            .trim(from: 0, to: 0.25)
            .stroke(Color.s500, lineWidth: 4)
            .frame(width: 40, height: 40)
            .rotationEffect(Angle(degrees: rotation))
            .onAppear {
                withAnimation(Animation.linear(duration: 1).repeatForever(autoreverses: false)) {
                    rotation = 360
                }
            }
    }
}

这种方式动画逻辑更直观,状态切换带来的异常概率更低。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:22:26