Search code examples
swiftswiftuiwidgetios14widgetkit

SwiftUI iOS 14 Widget CountDown


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?


Solution

  • 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.

    1. Create an Entry where displayDate is the total time (here 1 minute):
    struct SimpleEntry: TimelineEntry {
        let date: Date
        let displayDate: Date
        var isDateClose = false
    }
    
    1. In your Provider create two Entries - one for the standard color and one for the isClose color (here red):
    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)
        }
    }
    
    1. Use it in your view:
    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.