swiftuiwidgetkit

Right-aligning Text(Date(), style: .timer) text in an iOS WidgetKit widget


Here's an interesting quandary: I want to make a timer that "ticks" reliably but, also, renders symbols in predictable places so that I could, for instance, decorate the timer by adding a background. Because of WidgetKit limitations, I cannot reliably render my own text every second and have to rely on special views, such as Text(Date(), style: .timer). However, this view can render time as, both, XX:XX and X:XX depending on how much time is left, which would be OK, except, it also, both, takes the whole width of the container and aligns to the left, which makes the last :XX move depending on time left.

Here's an illustration:

enter image description here

And code that produced it:

struct MyWidgetEntryView : View {    
    var body: some View {
        VStack {
            Text(Date().addingTimeInterval(1000), style: .timer)
                .font(.body.monospacedDigit())
                .background(Color.red)
            
            Text(Date().addingTimeInterval(100), style: .timer)
                .background(Color.green)
                .font(.body.monospacedDigit())
        }
    }
}

Question: is there a way to make a reliably updating time display in a WidgetKit widget in such a way that symbols for minutes and seconds are always rendered in the same places and not move depending on time left?

I can't figure it out, please help me!

–Baglan


Solution

  • Set the multi-line text alignment:

    Text(Date(), style: .timer)
        .multilineTextAlignment(.trailing)
    

    It’s not multiple lines of text but it works!