selva
selva

Reputation: 809

macOS how to group and focus more than one labels during VoiceOver accessibility

My view hierarchy is: A parent view, a container view which is subview of parent view. The container view has multiple labels as a key value pair. Eg: Name: Somename. Something like under "Simplify Your Accessibility Information" Labels without grouping.

Note: My question is for macOS, I just gave iOS for reference.

VoiceOver reads key and value as separately but I want them to be read as one label and focus also as single label.

I tried to setAccessibilityFrameInParentSpace and NSAccessibilityElement. But still VoiceOver reads and focus separately. Code:

    func setAccessibility() {
    
    var elements = [NSAccessibilityElement]()
    let groupedElement = NSAccessibilityElement()
    groupedElement.setAccessibilityLabel("\(nameLabel.stringValue), \(nameValue.stringValue)")
    //groupedElement.setAccessibilityFrame(nameLabel.frame.union(nameValue.frame))
    groupedElement.setAccessibilityFrameInParentSpace(nameLabel.frame.union(nameValue.frame))
    elements.append(groupedElement)
    /*
    nameLabel.setAccessibilityLabelUIElements(elements)
    nameValue.setAccessibilityLabelUIElements(elements)
    nameLabel.setAccessibilityLabel("\(nameLabel.stringValue), \(nameValue.stringValue)")
    nameLabel.setAccessibilityFrame(nameLabel.frame.union(nameValue.frame))
    */
    
    containerView.setAccessibilityLabelUIElements([elements])
}

I referred macOS accessibility. Something still I'm missing. Individual labels are set accessibility enabled. Like

setAccessibilityElement(true)
setAccessibilityRole(.staticText)

Appreciate your input.

Thanks

Upvotes: 0

Views: 1098

Answers (1)

Nick K9
Nick K9

Reputation: 4718

The right way to do this is to use NSAccessibilityProtocol.setAccessibilityTitleUIElement(_:). Let's imagine you have a UI which looks like this:

enter image description here

To associate these two fields, you would use the API like this. Note that you need to associate the CELL of the title field with the control which needs a title:

usernameField.setAccessibilityTitleUIElement(usernameLabel.cell)

By default, this will lead VoiceOver to announce two elements: "Username:" and "user1 insertion at end of text, Username:, edit text". If users have enabled the "Skip redundant labels" setting in VoiceOver Utility > Navigation, then VoiceOver wouldn't even land on the Username: label at all.

In addition to doing this in code, you can also make the association easily by dragging from the control's context menu in Xcode:

enter image description here

Upvotes: 1

Related Questions