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
Answered by Engineer in 656330022
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 */)

Accepted Answer
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 */)

Works perfectly. Thank you!

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

The solution for me was to create an un-styled GroupBox to "wrap" any content inside.
After that we can assign an accessibilityIdentifier to it.
It doesn't disrupt the screen readers or change the layout.

Code:

/// Groupbox "no-op" container style without label
/// to combine the elements for accessibilityId
struct ContainerGroupBoxStyle: GroupBoxStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.content
    }
}

extension GroupBoxStyle where Self == ContainerGroupBoxStyle {
    static var contain: Self { Self() }
}

extension View {
    /// This method wraps the view inside a GroupBox
    /// and adds accessibilityIdentifier to it
    func groupBoxAccessibilityIdentifier(_ identifier: String) -> some View {
        GroupBox {
            self
        }
        .groupBoxStyle(.contain)
        .accessibilityIdentifier(identifier)
    }
}

Usage:

struct TestView: View {
    var body: some View {
        HStack {
            Image(systemName: "person")
            TextField("Name", text: .constant("Name"))
        }
        .padding()
        .onTapGesture {
            print("Stack Tap")
        }
        .groupBoxAccessibilityIdentifier("NAME_TEXTFIELD")
    }
}
SwiftUI: Adding accessibility identifiers to VStack
 
 
Q