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

macOS Swift应用中圆形ProgressView无法实现动画的问题求助

macOS SwiftUI 圆形ProgressView动画不生效的解决方法

问题场景

在macOS的SwiftUI应用中,线性样式的ProgressView可通过.animation修饰符正常呈现进度动画,但设置.progressViewStyle(.circular)的圆形ProgressView动画完全无反应。

原因

macOS的圆形ProgressView底层基于NSProgressIndicator,其动画触发逻辑和线性ProgressView存在差异。直接给视图添加.animation修饰符无法正确驱动它的进度动画,需要通过状态更新时的动画包裹来触发。

解决步骤

  1. 移除ProgressView上的.animation修饰符
  2. 更新进度值时,用withAnimation包裹赋值操作,让SwiftUI统一处理动画逻辑

完整示例代码

import SwiftUI

struct ContentView: View {
    @State private var progressAction1 = 0.0
    
    var body: some View {
        VStack(spacing: 40) {
            // 线性ProgressView
            ProgressView(value: progressAction1)
            
            // 圆形ProgressView
            ProgressView(value: progressAction1)
                .progressViewStyle(.circular)
            
            Button("切换进度") {
                withAnimation(.easeIn(duration: 1)) {
                    progressAction1 = progressAction1 == 1.0 ? 0.0 : 1.0
                }
            }
        }
        .padding()
    }
}

说明

通过withAnimation包裹进度值的修改,SwiftUI会自动将动画应用到所有依赖该状态的视图上,包括圆形ProgressView,以此实现和线性样式一致的平滑动画效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 09:46:04