burhanaksendir
burhanaksendir

Reputation: 11

How to Format Timer Style Text in SwiftUI with Leading Zeros?

I'm currently working on a SwiftUI project and I'm using the .timer style with a Text view to display a time duration. However, I'm having trouble formatting it to include leading zeros for hours, minutes, and seconds.

Here's the code I'm using:

struct ContentView: View {
    var body: some View {
       
        let components = DateComponents(hour: 2, minute: 15, second: 12)
        let futureDate = Calendar.current.date(byAdding: components, to: Date())!

        Text(futureDate, style: .timer)
            .font(.title)
            .frame(width: 120)
    }
}

The output I get is: 2:15:12, but I would like it to be: 02:15:12.

Could anyone please help me with the appropriate SwiftUI code to achieve this formatting with the .timer style? Your assistance would be greatly appreciated.

As a follow-up, I have reviewed the documentation provided at https://developer.apple.com/documentation/widgetkit/displaying-dynamic-dates but unfortunately,

Upvotes: 0

Views: 1517

Answers (1)

malsag
malsag

Reputation: 203

If you specifically want to use .timer style I don't think there is direct way to customize its formatting, as the .timer style in SwiftUI takes care of the countdown for you. But you can easily achieve same thing using Timer publisher and adjusting DateFormatter as you need

struct ContentView: View {
    @State private var time = Date()
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm:ss"
        return formatter
    }()
    
    var body: some View {
        Text(dateFormatter.string(from: time))
            .font(.title)
            .frame(width: 120)
            .onReceive(timer) { _ in
                time = Date()
            }
    }
} 

Upvotes: 0

Related Questions