SwiftUI: Adding accessibility identifiers to VStack

The goal is to add accessibility identifiers to a VStack where the VStack, View1, and View2 have their own, separate accessibility identifiers set, like so:

Code Block
           VStack { // identifier a
             View1 // identifier b
             View2 // identifier c
          }


When trying to use .accessibilityIdentifier(identifier) with any SwiftUI Stack, the identifier is applied to everything inside the VStack and overrides any identifiers that View1 or View2 may have had.

The current workaround is to use a GroupBox Container View to wrap the VStack. It achieves the desired result of having different levels of accessibility identifiers but has the drawback of coming with some styling (adds padding).


Is there a better way to go about adding accessibility identifier to a container view?

See Example playground

Accepted Reply

You can call the accessibilityElement modifier on the VStack to create a separate element for it:

Code Block
VStack {
}
.accessibilityElement(children: .contain)
.accessibilityIdentifier(/* VStack identifier */)

Add a Comment

Replies

You can call the accessibilityElement modifier on the VStack to create a separate element for it:

Code Block
VStack {
}
.accessibilityElement(children: .contain)
.accessibilityIdentifier(/* VStack identifier */)

Add a Comment
Works perfectly. Thank you!
  • was working great until we noticed that our memory footprint grown from 45 Mb to 2.5 Gb and keeps growing if user is using accessibility features.

Add a Comment

Hey Sparta. Has the memory leak subject been resolved? Thanks for letting me know