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.

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.

Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover

Check out our book!

Integrating SwiftUI into UIKit Apps

Integrating SwiftUI intoUIKit Apps

UPDATED FOR iOS 17!

A detailed guide on gradually adopting SwiftUI in UIKit projects.

  • Discover various ways to add SwiftUI views to existing UIKit projects
  • Use Xcode previews when designing and building UI
  • Update your UIKit apps with new features such as Swift Charts and Lock Screen widgets
  • Migrate larger parts of your apps to SwiftUI while reusing views and controllers built in UIKit