Black Friday 2024 deal: 30% off our Swift and SwiftUI books! Learn more ...Black Friday 2024 deal:30% off our Swift and SwiftUI books >>
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.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Black Friday 2024 offer: 30% off!$35$25

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms
Black Friday 2024 offer: 30% off!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35$25