Reputation: 1747
Is there a way to set the accessibility focus programatically (App Store safe)? Any help will be greatly appreciated.
Upvotes: 55
Views: 61046
Reputation: 1011
UIAccessibility.post(notification: .layoutChanged, argument: toast)
toast.becomeFirstResponder()
toast.isAccessibilityElement = true
toast.accessibilityTraits = .staticText //Traits option ie .header, .button etc
toast.accessibilityLabel = "Accessibility label to be read by VoiceOver goes here"
WHERE:
toast
is my UIView (a pop up which gets triggered upon particular scenario)View
toast
) and VoiceOver will read accessibilityLabel
Upvotes: 0
Reputation: 5938
To focus on element you can call.
Swift:
UIAccessibility.post(notification: .screenChanged, argument: self.myFirstView)
ObjC:
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, self.myFirstView);
Otherwise for iOS 8+ use the accessibilityElements to set element order and it will focus automatically on first element in the list
self.accessibilityElements = @[myFirstView, mySecondButton, myThirdLabel]
Upvotes: 75
Reputation: 121
extension UIAccessibility {
static func setFocusTo(_ object: Any?) {
if UIAccessibility.isVoiceOverRunning {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
UIAccessibility.post(notification: .layoutChanged, argument: object)
}
}
}
}
Add this extension and call it by passing in the view you would like to be focused. If you would like to change focus when navigating using a tabbar, you can call this from viewWillAppear. This code wont work in any init method without a the delay of 0.7 or more.
Upvotes: 12
Reputation: 184
This is the Swift code:
UIAccessibility.post(notification: .screenChanged, argument: <theView>)
Example usage
let titleLabel = UILabel()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIAccessibility.post(notification: .screenChanged, argument: titleLabel)
}
Upvotes: 2