iOS15下SwiftUI圆形进度条动画失效及弃用警告解决求助
问题解决说明
核心原因
iOS 15 开始SwiftUI废弃了无参数的animation(_:)接口,旧写法不会自动监听状态变化触发动画,同时会抛出弃用警告,只要替换为官方推荐的animation(_:value:)接口即可同时解决两个问题。
1. 圆形ProgressBar修复方案
修改ProgressBar里圆形描边的动画修饰符,给animation增加value参数绑定到progress属性即可,动画会在progress值变化时自动触发,同时消除弃用警告。
修正后的完整ProgressBar代码如下:
struct ProgressBar: View { @Binding var progress: Float var body: some View { ZStack { Circle() .stroke(lineWidth: 20.0) .opacity(0.3) .foregroundColor(Color.red) Circle() .trim(from: 0.0, to: CGFloat(min(self.progress, 1.0))) .stroke(style: StrokeStyle(lineWidth: 20.0, lineCap: .round, lineJoin: .round)) .foregroundColor(Color.red) .rotationEffect(Angle(degrees: 270.0)) // 仅修改这一行,绑定value为progress .animation(.linear, value: progress) Text(String(format: "%.0f %%", min(self.progress, 1.0)*100.0)) .font(.largeTitle) .bold() } } }
2. 最初版本代码修复方案
初始版本动画触发依赖showFreespaceRing的状态变化,所以给animation绑定value为showFreespaceRing即可:
Circle() .trim(from: 0, to: showFreespaceRing ? CGFloat(Double(freeDiskspace) / Double(totalDiskspace)) : 0) .stroke(Color.green.opacity(0.7), style: StrokeStyle(lineWidth: 10, lineCap: .round)) .frame(width: circleDiam, height: circleDiam) // 仅修改这一行,绑定value为showFreespaceRing .animation(.easeIn(duration: 1), value: showFreespaceRing) .onAppear() { showFreespaceRing = true }
内容的提问来源于stack exchange,提问作者iKK
相关产品推荐
相关产品推荐

