我有一个带有倒计时的iOS 14小部件
Text(foo, style: .timer)
时间少于1分钟时如何将文本颜色更改为红色?
答案 0 :(得分:2)
在这里,您可以为1 minute
创建倒计时,将文本颜色向左10 seconds
更改为红色。时间到了,倒数再次开始。
displayDate
是总时间(此处为1分钟):struct SimpleEntry: TimelineEntry {
let date: Date
let displayDate: Date
var isDateClose = false
}
struct SimpleProvider: TimelineProvider {
...
func getTimeline(in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> Void) {
let currentDate = Date()
let firstDate = Calendar.current.date(byAdding: .second, value: 50, to: currentDate)!
let secondDate = Calendar.current.date(byAdding: .second, value: 60, to: currentDate)!
let entries = [
SimpleEntry(date: currentDate, displayDate: secondDate),
SimpleEntry(date: firstDate, displayDate: secondDate, isDateClose: true),
]
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
struct SimpleWidgetEntryView: View {
var entry: SimpleProvider.Entry
var body: some View {
Text(entry.displayDate, style: .timer)
.foregroundColor(entry.isDateClose ? .red : .primary)
}
}
这里是一个GitHub repository,带有不同的窗口小部件示例,包括倒数窗口小部件。