在WidgetKit中每分钟更新时间文本标签 [英] Updating time text label each minute in WidgetKit
本文介绍了在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
- 您需要一个具有
Date
属性的简单Entry
:
- You need a simple
Entry
with aDate
property:
struct SimpleEntry: TimelineEntry {
let date: Date
}
- 每分钟创建一个
Entry
,直到下一个午夜:
- Create an
Entry
every minute until the next midnight:
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)
}
}
- 使用
time
样式显示日期:
- 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存储库,其中包含不同的小部件示例,包括Clock小部件.
Here is a GitHub repository with different Widget examples including the Clock Widget.
这篇关于在WidgetKit中每分钟更新时间文本标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文