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