如何阻止倒计时圆环动画反向播放并重置为初始状态?
解决倒计时圆环在pct=1.0时反向动画的问题
你的问题出在当pct到达1.0时,trim的to参数从接近1的数值直接跳到1,后续若pct重置为0,动画会反向播放。要实现到达1.0后重新从0开始,需调整动画逻辑:
修改后的代码
struct ActivityCircle : View { let color: UIColor let pct: CGFloat @State var progress: CGFloat = 0.0 var body: some View { Circle() .trim(from: 0, to: progress) .rotation(Angle(degrees: -90)) .stroke(style: StrokeStyle(lineWidth: 13, lineCap: .round, lineJoin: .round)) .foregroundColor(Color(color)) .onChange(of: pct) { oldValue, newValue in print("Old value is \(oldValue)") print("New value is \(newValue)") if newValue == 1.0 { // 先动画到满环 withAnimation(.linear(duration: 1.0)) { progress = 1.0 } // 动画结束后,无动画重置为0,为下一次循环做准备 DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { withAnimation(nil) { progress = 0.0 } } } else { // 正常进度更新动画 withAnimation(.linear(duration: 1.0)) { progress = newValue } } } } }
关键修改点
- 移除了原代码中
newValue == 0时设置progress = 1.0的错误逻辑,这是导致反向动画的根源之一 - 新增
pct == 1.0的处理分支:先通过动画将圆环填满,然后在动画时长后,无动画地将progress重置为0,确保下一次pct从0开始时,动画是正向从0到目标值,而非反向 - 保持正常进度更新时的线性动画逻辑
这样修改后,当pct到达1.0时,圆环会平滑动画到满,然后瞬间重置为0,后续再接收0到0.99的pct值时,就会从0开始正向动画。
内容的提问来源于stack exchange,提问作者desmeit
相关产品推荐
相关产品推荐

