Reputation: 37
I have a iOS 14 widget with a Countdown
Text(foo, style: .timer)
How can I change text color to red when the time is less than 1 minute?
Upvotes: 3
Views: 3397
Reputation: 54486
Here is how you can create a countdown for 1 minute
with the text color changing to red when it's 10 seconds
left. When the time is over the countdown starts again.
displayDate
is the total time (here 1 minute):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)
}
}
Here is a GitHub repository with different Widget examples including the Countdown Widget.
Upvotes: 5