ios - Swiftui:如何在导航标题上添加辅助功能标识符

标签 ios swift swiftui navigation uikit

我们如何将 Accessibility Identifier 添加到 NaviagationTitle 文本。我知道对于按钮/文本/图像/堆栈 View ,我们可以使用 .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"))
       }
   }
无法将修饰符添加到 .navigationBarTitle(Text(“title”), displayMode: .inline) 。 XCUI 自动化测试需要可访问性标识符。

最佳答案

我认为这在使用 .accessibility(identifier:) 的 SwiftUI 中是不可能的 - 可能值得向 Apple 提交反馈。
但是,您仍然可以通过其标识符访问导航栏 - 只是默认标识符是文本:

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

或者,您可以尝试使用辅助扩展(改编自 here )访问 UINavigationBar:
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)
        }
    }
}
现在您可以从 SwiftUI View 访问 UINavigationBar:
struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("text")
                .navigationTitle("title")
                .background(
                    NavigationBarAccessor {
                        $0?.accessibilityIdentifier = "id123"
                    }
                )
        }
    }
}
请注意,在上面的示例中,您将 accessibilityIdentifier 设置为 UINavigationBar 本身,而不是直接设置为标题。

关于ios - Swiftui:如何在导航标题上添加辅助功能标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66166652/

相关文章:

ios - 如何在 iOS 和 tvOS 上使用相同的 pod?

generics - 在 Swift 中扩展泛型?

SwiftUI:如何强制将HStack中的特定 View 置于中心

SwiftUI New App生命周期如何连接Facebook SDK

ios rectOfInterest AVCaptureMetadataOutput 忽略

android - Kentico CMS 支持 native iOS 和 Android

ios - 如何为 Data swift 添加扩展?

SwiftUI AppStorage、UserDefaults 和 ObservableObject

ios - 使用 UI 测试测试操作扩展

iphone - 当我使用 CPTPGraphHostingView [核心图] 时,背景 ImageView 是颠倒的(翻转)