Day 15

Use formatters for abbreviation labels

2 Jun 2022

Tip for abbreviations. Something like "3h 24m" will be read by VoiceOver as "3 h 24 meters". Formatters can help. DateComponentsFormatter with a "spellOut" units style will give you a more suitable label: "three hours, twenty-four minutes"

Code shows how you can create a DateComponentsFormatter, configure its allowed units and the units style with spell out, and you can get a human readable string representing the time from it, by passing a time interval.

Example code in the image:

let dailyAverageLabel = UILabel()
let abbreviatedReadableFormatter = DateComponentsFormatter()

abbreviatedReadableFormatter.allowedUnits = [.hour, .minute]
abbreviatedReadableFormatter.unitsStyle = .spellOut

let abbreviatedReadableDuration = abbreviatedReadableFormatter.string(from: 12240)

dailyAverageLabel.accessibilityLabel = abbreviatedReadableDuration

Some useful links:

* Date Components Formatter:

* Units Style:

By the way! Formatters are also great for localisation.

Some of you have asked me how you can support what I do. This would really help, and would be hugely appreciated:

  • Find these posts useful? Share them at work, on social media, or with anyone that might find them interesting. Let's spread the word!

  • Check out any of my apps or games: Xarra!, RetroRapid!, or Mestre!.

    • A download and a review go a long way. They're free by default. On the App Store, ratings and reviews really help more people discover them.

    • Finding any of them useful? If so, and if you can afford it, purchasing lifetime access to all features or subscribing lets me buy the coffee that keeps me caffeinated. Caffeine keeps me going to maintain the apps, bring in new features that I hope you'll love, and keep writing.

You may also find interesting...

Accessibility Labels are not just for VoiceOver, and Accessibility User Input Labels are not just for Voice Control. The latter will also help Full Keyboard Access users to find elements on the screen by different names. Good API design!

Even when setting a view as modal for accessibility, you may notice that VoiceOver's focus stays in the same place, instead of moving to the presented view. You can post a screen changed notification and pass the view that should get the focus.

Have you ever seen VoiceOver randomly focusing on elements of the previous view when presenting a custom modal view? That can be fixed by letting the system know that the presented view is modal in terms of accessibility.


Content © Daniel Devesa Derksen-Staats on Accessibility up to 11! is licensed under CC BY 4.0. License details