Enhance Basic Accessibility of SwiftUI Views

Jyothish Johnson
3 min readMar 14, 2021

--

Photo by Daniel Ali @untodesign_

As mobile developers, it is our responsibility to make our apps as much accessible as possible whenever relevant. I believe it shows the amount of care that has been put into developing the product.

So today, let's discuss a few modifiers in SwiftUI that will help us enhance the basic accessibility that already comes built-in with SwiftUI views, but is not user friendly in most cases.

Let’s see a basic example of Voice-over built into a SwiftUI view, we will enhance it along the way.

VoiceOver Output: “Barca image Juve image Juventus 2 3 Barcelona”

As you can understand, this output is not helpful for the user, also it’s misleading in our case (Juv 3 - 2 Barca). So let’s improve it.

1. accessibilityElement(children:)

This helps to modify the child accessibility elements inside a view. In our case, step 1: We can use this on our VStack to first ignore the child accessibility elements and add custom labels or value later.

Image Credit https://ray.so/

2. accessibilityLabel(_:)

This modifier helps us to add a custom accessibility label to our views. We can use this when we need to provide an accessibility label for a view or a combined view that doesn’t really have a textual representation. (ie: Buttons, Controls)

So in our case, after ignoring the child accessibility elements, step 2: We add a custom accessibility label according to our needs to relay the relevant and correct information to the user.

Image Credit https://ray.so/

VoiceOver output: “Barcelona scored 2 goals and Juventus scored 3 goals

As you can see, this voiceover output much more user friendly.

3. accessibilityValue(_:)

You can achieve the same results as above with this modifier also. We can use this modifier whenever the automatic textual representation of a view doesn’t really convey a meaningful message to the user.

4. Accessibility Traits

Some of the default views in SwiftUI have built-in accessibility traits, which help voice-over to add default labels to such views.

For example, Button has an accessibility trait of “isButton” and Image has an accessibility trait of “isImage”, these automatically add “Button” and “Image” labels to the end of the auto-generated accessibility label.

Whenever appropriate we can add and remove such built-in accessibility traits using

  1. accessibilityAddTraits(_:)
  2. accessibilityRemoveTraits(_:)

You can find all the available SwiftUI accessibility traits here

Thank you for reading. Share it with your teammates if you find it useful!

Find the final code here

--

--

No responses yet