Post accessibility notification in SwiftUI

1.7k Views Asked by At

I need to move the accessibility focus to a certain element on the screen. In UIKit, I can simply call UIAccessibility.post(.screenChanged, element).

When I do that with a SwiftUI View, the app crashes with the following message in console:

This class '__SwiftValue' is not a known serializable element and returning it as an accessibility element may lead to crashes

Any idea how I can move focus to certain elements on the screen in SwiftUI?

2

There are 2 best solutions below

0
FrugalResolution On

A workaround would be: Post a notification when the UIView appears:

    .onAppear(perform: {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            UIAccessibility.post(notification: .screenChanged, argument: "New Screen")
        }
    })

As argument it would make sense to put in the text of the accessibility label of the desired view. The impaired user would just not know where the screenReader is focusing if the user could recognize the white surrounding of the screenReader focus.

To make things smooth the delay of 0.1 should be adapted while testing with different languages.

0
PaulJam On

Try accessibilityFocused(_:equals:)

enum FocusedView: Hashable {
     case A
}

SomeView {
    @AccessibilityFocusState var focus: FocusedView?

    var body: some View {
        SomeButton()
           .accessibilityFocused($focus, equals: .A)
    }
}

If you want set focus to SomeButton,

focus = .A