在 WidgetKit 中每分钟更新时间文本标签 [英] Updating time text label each minute in WidgetKit

查看:26
本文介绍了在 WidgetKit 中每分钟更新时间文本标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Widget 中创建显示当前时间并实时更新的文本标签?

Is it possible to create text label in Widget that will show current time and will be updating in real-time?

尝试创建时钟小部件,但小部件每 5 分钟仅更新 1 次.

Trying to create clock widget, but widget is updating only 1 time each 5 minutes.

  • 没有帮助创建时间线
  • 使小部件保持最新状态"不使用当前时间,只使用计时器等.

推荐答案

一个可能的解决方案是使用 time 日期样式:

A possible solution is to use the time date style:

/// A style displaying only the time component for a date.
///
///     Text(event.startDate, style: .time)
///
/// Example output:
///     11:23PM
public static let time: Text.DateStyle


  1. 您需要一个带有 Date 属性的简单 Entry:
  1. You need a simple Entry with a Date property:

struct SimpleEntry: TimelineEntry {
    let date: Date
}

  1. 每分钟创建一个条目,直到下一个午夜:

struct SimpleProvider: TimelineProvider {
    ...

    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
        var entries = [SimpleEntry]()
        let currentDate = Date()
        let midnight = Calendar.current.startOfDay(for: currentDate)
        let nextMidnight = Calendar.current.date(byAdding: .day, value: 1, to: midnight)!

        for offset in 0 ..< 60 * 24 {
            let entryDate = Calendar.current.date(byAdding: .minute, value: offset, to: midnight)!
            entries.append(SimpleEntry(date: entryDate))
        }

        let timeline = Timeline(entries: entries, policy: .after(nextMidnight))
        completion(timeline)
    }
}

  1. 使用time样式显示日期:
  1. Display the date using the time style:

struct SimpleWidgetEntryView: View {
    var entry: SimpleProvider.Entry

    var body: some View {
        Text(entry.date, style: .time)
    }
}


如果你想自定义日期格式,你可以使用自己的DateFormatter:

struct SimpleWidgetEntryView: View {
    var entry: SimpleProvider.Entry
    
    static let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "HH:mm"
        return formatter
    }()

    var body: some View {
        Text("(entry.date, formatter: Self.dateFormatter)")
    }
}


这是一个 GitHub 存储库,其中包含不同的小部件示例,包括时钟小部件.


Here is a GitHub repository with different Widget examples including the Clock Widget.

这篇关于在 WidgetKit 中每分钟更新时间文本标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆