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

如何在watchOS WidgetKit中显示精简版相对日期计时器?

问题:SwiftUI Text视图能否实现watchOS Complications的缩写相对日期显示?

我正在使用WidgetKit和SwiftUI开发watchOS complication,尝试为Text视图应用日期样式,但当前显示的是长格式。相关代码示例如下:

import SwiftUI
import WidgetKit

struct MyGaugeCircularAccessoryView: View {
    let gradient = Gradient(stops: [.init(color: .red, location: 0), .init(color: .green, location: 0.25)])

    var body: some View {
        Gauge(value: 0.6) {
            Text("ABC")
        } currentValueLabel: {
            Text(.now + 60 * 60 * 3, style: .relative)
        }
        .gaugeStyle(.accessoryCircular)
        .tint(gradient)
    }
}

struct MyGaugeCircularAccessoryView_Previews: PreviewProvider {
    static var previews: some View {
        MyGaugeCircularAccessoryView()
            .previewContext(WidgetPreviewContext(family: .accessoryCircular))
    }
}

当前显示效果为长文本样式,而此前我可通过CLKRelativeDateTextProvider(date: .now, style: .naturalAbbreviated, units: [.hour])实现精简缩写的相对日期显示,请问是否可通过Text(date:style:)视图达成同样效果?


回答

SwiftUI原生的Text(date:style:)的.relative样式没有直接提供缩写配置选项,但可以通过自定义RelativeDateTimeFormatter来实现和CLKRelativeDateTextProvider的.naturalAbbreviated一致的缩写效果。

修改后的代码示例:

import SwiftUI
import WidgetKit

struct MyGaugeCircularAccessoryView: View {
    let gradient = Gradient(stops: [.init(color: .red, location: 0), .init(color: .green, location: 0.25)])
    
    // 自定义缩写相对日期格式化器
    private let abbreviatedRelativeFormatter: RelativeDateTimeFormatter = {
        let formatter = RelativeDateTimeFormatter()
        formatter.unitsStyle = .short // 对应naturalAbbreviated的缩写效果
        formatter.locale = Locale.current
        // 可选:限制仅显示指定时间单位,比如只显示小时
        formatter.allowedUnits = [.hour]
        return formatter
    }()
    
    var targetDate: Date {
        .now + 60 * 60 * 3
    }

    var body: some View {
        Gauge(value: 0.6) {
            Text("ABC")
        } currentValueLabel: {
            // 使用自定义格式化器生成缩写文本
            Text(abbreviatedRelativeFormatter.localizedString(for: targetDate, relativeTo: .now))
        }
        .gaugeStyle(.accessoryCircular)
        .tint(gradient)
    }
}

struct MyGaugeCircularAccessoryView_Previews: PreviewProvider {
    static var previews: some View {
        MyGaugeCircularAccessoryView()
            .previewContext(WidgetPreviewContext(family: .accessoryCircular))
    }
}

说明

  • 设置unitsStyle = .short后,格式化器会生成类似"3h"的缩写文本,和CLKRelativeDateTextProvider的.naturalAbbreviated效果匹配。
  • 通过allowedUnits参数可以精准控制显示的时间单位,避免多余的单位展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:25:33