Search code examples
iosaccessibilityuiswitchvoiceover

How can I make an arbitrary UIAccessibilityElement behave like a UISwitch for VoiceOver?


When selecting a native switch with VoiceOver, the announcement will contain "Off" or "On" with an additional hint "double tap to toggle setting".

I have tried using the accessibility trait UIAccessibilityTraitSelected, but that only results in "Selected" being announced, with no hint unless I provide one explicitly.

Using the Accessibility Inspector I've also noticed that native UIKit switches have an accessibilityValue of 1 when enabled, but providing that does not change VoiceOver behavior.

- (UIAccessibilityTraits)accessibilityTraits {
  if (toggled) {
    return UIAccessibilityTraitSelected;
  } else {
    return UIAccessibilityTraitNone;
  }
}

- (NSString*)accessibilityValue {
  if (toggled) {
    return @"1";
  } else {
    return @"0"
  }
}

Is it possible to provide some combination of traits/value/label such that TalkBack recognizes this element as a Switch, without using a UISwitch?


Solution

  • I have created an accessible view that acts like a switch here.

    The only way that I have been able to get any arbitrary element to act like a Switch is when inheriting the UIAccessibilityTraits of a Switch. This causes VoiceOver to read the Accessibility Value (0 or 1) as "Off" or "On," adds the hint "Double tap to toggle setting", and makes VoiceOver say "Switch Button."

    You could potentially do this by overriding the view's Accessibility Traits like so:

    override var accessibilityTraits(): UIAccessibilityTraits {
        get { return UISwitch().accessibilityTraits }
        set {}
    }
    

    Hope this helps!