我有一个带有倒计时的 iOS 14 小部件
Text(foo, style: .timer)
当时间少于 1 分钟时,如何将文本颜色更改为红色?
这是创建倒计时的方法,文本颜色在离开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 存储库,其中包含不同的 Widget 示例,包括 Countdown Widget。