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

SwiftUI Live Activity锁屏时显示--而非秒数的问题求助

SwiftUI倒计时锁屏秒数显示--的解决方法

问题说明

使用Text(timerInterval: context.state.deliveryTimer, countsDown: true)实现的倒计时,在iPhone解锁状态下能正常每秒更新显示(如1:30:50、1:30:49),但锁屏状态下秒数位置会变成--(如1:30:--)。

解决方法

1. 强制完整定时器格式

利用formatted方法指定完整显示模式,覆盖系统默认的锁屏简化逻辑:

Text(context.state.deliveryTimer, style: .timer)
    .formatted(.timer(presentation: .complete))

presentation: .complete参数会强制Text显示完整的时分秒,不受锁屏状态下的系统优化限制。

2. 手动实现倒计时逻辑(更可控)

放弃系统自带的timer样式,通过Timer.publish手动计算剩余时间并自定义格式化:

struct CountdownView: View {
    @Environment(\.state) private var state // 根据你的环境对象调整
    @State private var remainingSeconds: Int = 0
    private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    
    var body: some View {
        Text(countdownString)
            .onReceive(timer) { _ in
                guard remainingSeconds > 0 else {
                    timer.upstream.connect().cancel()
                    return
                }
                remainingSeconds -= 1
            }
            .onAppear {
                // 从TimerInterval初始化剩余秒数
                remainingSeconds = Int(state.deliveryTimer.timeIntervalSinceNow)
            }
    }
    
    private var countdownString: String {
        let hours = remainingSeconds / 3600
        let minutes = (remainingSeconds % 3600) / 60
        let seconds = remainingSeconds % 60
        return String(format: "%d:%02d:%02d", hours, minutes, seconds)
    }
}

这种方式完全自定义显示格式,不受系统锁屏下的显示策略影响,适配性更强。

原因解析

系统默认的Text(timerInterval:)在锁屏状态下,会出于功耗优化目的简化定时器显示,省略秒数的实时更新。通过强制完整格式或手动实现倒计时,可规避该系统行为。

内容的提问来源于stack exchange,提问作者Mhnd the basha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:52:03