Black Friday deal: 30% off our book "Integrating SwiftUI into UIKit apps"! Learn more ...Black Friday deal:30% off "Integrating SwiftUI into UIKit apps" >>
Quick Tip Icon
Quick Tip

Dynamic dates with monospaced digits in SwiftUI

When using the Text view in SwiftUI we can show dates and times that automatically update as time passes. To achieve it we can interpolate a date with a relative, offset or timer style inside the Text.

Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover
Black Friday offer
Our book "Integrating SwiftUI into UIKit apps" is now 30% off!

Discover various ways to adopt SwiftUI in existing UIKit projects and take full advantage of the new iOS 16 frameworks and APIs such as Swift Charts.

The offer is active until the 1st of December.

For example, we might want to show how much time is left until a particular event by interpolating the event date with a relative style. The Text view will display the difference between the current date and time and the specified date. SwiftUI will automatically keep it updated.

Text("\(eventDate, style: .relative) left until the event")
A gif showing that the time inside the text view automatically updates but the UI jitters

We can see that the time within the text dynamically changes but the UI jitters as digits update. This happens because by default digits have proportional width and different digits take a different amount of space.

To stop the UI from moving when the time changes, we can apply the monospacedDigit() modifier to the Text. It will force all the numeric characters take the same width independent of the digits they display. The other characters will remain unchanged.

Text("\(eventDate, style: .relative) left until the event")
    .monospacedDigit()
A gif showing that the time updates and the text doesn't change in width

With the monospacedDigit() modifier applied, the width of the text doesn't change every time the digits in the date get updated, which makes it a better visual experience.