7

How can we add the Accessibility Identifier to NaviagationTitle Text. I know for buttons/text/Image/stack views we can use .accessibility(identifier: “some_identifier”).

struct SomeView: View {
  var body: some View {
    VStack {
         Text("Title Text")
           .accessibility(identifier: "title")
           }
           .navigationTitle("title") //How to add accessibilityIdentifier to Navigation bar title?
           //.navigationTitle(Text("title").accessibility(identifier: "title"))
       }
   }

unable to add the modifier to .navigationBarTitle(Text(“title”), displayMode: .inline). Accessibility Identifiers are required for XCUI automation testing.

pawello2222
  • 46,897
  • 22
  • 145
  • 209
Pablo Dev
  • 317
  • 5
  • 16

1 Answers1

4

I don't think this is possible in SwiftUI using .accessibility(identifier:) - it might be worth submitting feedback to Apple.

However, you can still access the navigation bar by its identifier - just the default identifier is the text:

.navigationTitle("title")
let app = XCUIApplication()
app.launch()
assert(app.navigationBars["title"].exists) // true

Alternatively, you can try to access UINavigationBar using a helper extension (adapted from here):

struct NavigationBarAccessor: UIViewControllerRepresentable {
    var callback: (UINavigationBar?) -> Void
    private let proxyController = ViewController()

    func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationBarAccessor>) -> UIViewController {
        proxyController.callback = callback
        return proxyController
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationBarAccessor>) {}

    typealias UIViewControllerType = UIViewController

    private class ViewController: UIViewController {
        var callback: (UINavigationBar?) -> Void = { _ in }

        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            callback(navigationController?.navigationBar)
        }
    }
}

Now you can access UINavigationBar from a SwiftUI view:

struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("text")
                .navigationTitle("title")
                .background(
                    NavigationBarAccessor {
                        $0?.accessibilityIdentifier = "id123"
                    }
                )
        }
    }
}

Note that in the above example you set accessibilityIdentifier to the UINavigationBar itself and not to the title directly.

pawello2222
  • 46,897
  • 22
  • 145
  • 209