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.

  • Discover various ways to add SwiftUI to existing UIKit projects
  • Use Xcode previews when designing and building UI
  • Update your UIKit apps with iOS 16 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

Find out more…

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")

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 to take the same width independent of the digits they display. The other characters will remain unchanged.

Text("(eventDate, style: .relative) left until the event")
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.



Please enter your comment!
Please enter your name here