swiftuiaccessibility

How to call a function on HStack view in swiftUI


I want to call below function on HStack. I get no errors but accessibility is not set. I am sure I am doing something wrong but couldn't figure it out. I am new to swiftUI.

extension View {
    func setAccessibility(label: String, identifier: String, ignoreChildren: Bool) -> some View {
        if ignoreChildren {
            _ = accessibilityElement(children: .ignore)
        } else {
            _ = accessibilityElement()
        }
        _ = accessibilityIdentifier(identifier)

        _ = accessibilityLabel(label)

        return self
    }
}

Usage:

var body: some View {
    ZStack {
        HStack {
            Image(.logo)
                .resizable()
                .frame(width: UIConsts.logoImageHeight, height: UIConsts.logoImageHeight)
            Text("Hello")
            Spacer()
            Image(.arrowRight)
                .renderingMode(.template)
                .foregroundColor(.blue)
        }.frame(height: UIConsts.entryHeight)
        .setAccessibility(label: "Test label", identifier: "Test", ignoreChildren: true)
            
    }
}

Solution

  • Each of the accessibility modifiers that you are using returns a wrapped version of the view it is applied to. It is these wrappers that provide the functionality you are trying to add to the view.

    Currently, you are ignoring the return values that the modifiers deliver, which means the wrapped views are being dropped. So this will be why the modifiers do not appear to be working.

    ā†’ I would suggest chaining the modifiers together inside the extension and returning the end result.

    In the case of .accessibilityElement, the default parameter is .ignore. In other words, calling it without parameters is the same as calling it with a parameter of .ignore. So you might want to change the extension to accept a parameter of type AccessibilityChildBehavior, perhaps with .ignore as default?

    extension View {
        func setAccessibility(
            label: String,
            identifier: String,
            childrenAccessibility: AccessibilityChildBehavior = .ignore
        ) -> some View {
            self.accessibilityLabel(label)
                .accessibilityIdentifier(identifier)
                .accessibilityElement(children: childrenAccessibility)
        }
    }
    

    Example usage:

    HStack {
        // ...
    }
    .setAccessibility(label: "Test label", identifier: "Test")