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

Swift中如何刷新后台返回后的SRCountdownTimer环形动画匹配计时器进度

解决方案

你遇到的问题根源是iOS系统会在应用进入后台时自动冻结所有在执行的图层动画,恢复前台时默认延续冻结时的状态,不会主动和你的实际计时器数据对齐,按以下步骤修改即可:

  • 首先在你使用SRCountdownTimer的页面中监听应用回到前台的通知
// 页面初始化时添加监听
NotificationCenter.default.addObserver(self, selector: #selector(refreshTimerAnimation), name: UIApplication.willEnterForegroundNotification, object: nil)
  • 实现刷新动画的方法,先移除原有动画,再用当前实际的计时器进度刷新动画
@objc private func refreshTimerAnimation() {
    // 先移除环形图层上所有旧的进度动画
    if let progressLayer = countdownTimer.layer.sublayers?.first(where: { $0 is CAShapeLayer }) as? CAShapeLayer {
        progressLayer.removeAllAnimations()
    }
    // 传入当前剩余时间、总时长,让框架重新计算进度并渲染
    let currentRemainingTime: TimeInterval = // 此处替换为你自己的计时器当前实际剩余时间
    let totalTime: TimeInterval = // 此处替换为你的计时器总时长
    countdownTimer.updateTime(currentRemainingTime, totalTime: totalTime)
    // 如果计时器还在运行,直接调用resume方法恢复动画
    if 你的计时器当前是运行状态 {
        countdownTimer.resume()
    }
}
  • 页面销毁时移除通知监听避免内存泄漏
deinit {
    NotificationCenter.default.removeObserver(self)
}

如果你不需要自定义动画逻辑,也可以直接修改框架内部的SRCountdownTimer.swift文件,在init方法里统一添加前台通知监听,按照上面的逻辑内部处理动画刷新,业务侧就不用额外改动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:36:04