Day 229

accessibilityElement(children:) in SwiftUI

4 Jan 2023

In SwiftUI there is a very useful modifier accessibilityElement(children:), that will do very different things depending on the AccessibilityChildBehavior passed as a parameter. There are three options: ignore (default), contain, and combine.

accessibilityElement(children:) applied to a view consisting of an HStack, with two VStacks. The first one has three labels: A (with a as identifier), B (with b as identifier), and C (with 0 as value). The second one has two buttons: D and E (with 1 as value). This SwiftUI modifier has three possible options: Ignore, Contain and Combine. With ignore, the HStack is focusable but it will have no attributes, we need to configure them manually. With contain, there are 5 focusable elements, each one of the children. With combine, the HStack is focusable and the attributes are combined from the children. In this case: the label is

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...

If an image does not convey additional information, maybe it's just used to make the UI look more attractive, it makes sense for VoiceOver to skip it. UIKit: set isAccessibilityElement to false. SwiftUI: create a decorative image explicitly.

The equivalent of using a .semanticGroup accessibilityContainerType in UIKit, would be to use the .accessibilityElement(children: ) modifier with the .contain option in SwiftUI. Here's a refresher with some use-cases: https://x.com/dadederk/status/1558790851496742914

It is possible to change the traversing order of accessibility elements by configuring the accessibilityElements array. You should try to avoid it, but one good reason for doing it is if the default order is illogical because of the visual layout.


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