Search code examples
iosswiftaccessibilityvoiceoveruiaccessibility

Set different behaviour when VoiceOver is on, in stack view with buttons


I have a custom stack view with two buttons side by side. When VoiceOver is on, I want it to read these two buttons as some sort of tab, like "Button X Item 1 of 2" and "Button Y Item 2 of 2". Is it possible ?

My view controller have the following:

@IBOutlet weak var buttonAdd: UIButton!
@IBOutlet weak var buttonDelete: UIButton!
@IBOutlet weak var selector: CustomSelectorStackView!

I tried adding to my viewDidLoad:

accessibilityElements = [buttonAdd, buttonDelete]

and changing the trait of the buttons but no success.

What traits or other accessibility elements should I add to viewDidLoad so I can achieve the desired output.


Solution

  • You can use the Accessibility Label property to allow VoiceOver to read whatever you'd like:

    let buttons = [buttonAdd, buttonDelete]

    for button in buttons {
        button.accessibilityLabel = "\(button), Item \(x) of \(buttons.count)"
    }
    

    You can also add it as a hint (but be aware that some VoiceOver users turn off hints):

    for button in buttons {
        button.accessibilityLabel = button
        button.accessibilityHint = "Item \(x) of \(buttons.count)"
    }
    

    These examples assume that the visible text is understandable to a VoiceOver user, such as "Add Button" or "Delete Button." If the text isn't understandable, or if you've used an image instead of text, use the accessibilityLabel to assign understandable text. However, in this example, you won't be able to iterate through, you'll have to assign the label to each button individually. You can then either append the tab number to the label, or iterate through to assign them to the hint.

    buttonAdd.accessibilityLabel = "Add Button"
    buttonDelete.accessibilityLabel = "Delete Button"
    

    Essentially, there are multiple ways to accomplish what you have described, and these are just a few examples.

    This guide is immensely helpful: http://a11y-guidelines.orange.com/mobile_EN/dev-ios.html