Swiftui:如何在导航标题上添加辅助功能标识符 [英] Swiftui: How to add Accessibility Identifier on navigationTitle
问题描述
我们如何将 Accessibility Identifier
添加到 NaviagationTitle 文本.我知道对于按钮/文本/图像/堆栈视图,我们可以使用 .accessibility(identifier: some_identifier")
.
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"))
}
}
无法将修饰符添加到 .navigationBarTitle(Text(title"), displayMode: .inline)
.XCUI 自动化测试需要辅助功能标识符.
unable to add the modifier to .navigationBarTitle(Text("title"), displayMode: .inline)
. Accessibility Identifiers are required for XCUI automation testing.
推荐答案
我认为这在 SwiftUI 中使用 .accessibility(identifier:)
是不可能的 - 可能值得向 Apple 提交反馈.
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
或者,您可以尝试使用辅助扩展(改编自 此处)访问 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 视图访问 UINavigationBar
:
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"
}
)
}
}
}
请注意,在上面的示例中,您将 accessibilityIdentifier
设置为 UINavigationBar
本身,而不是直接设置为标题.
Note that in the above example you set accessibilityIdentifier
to the UINavigationBar
itself and not to the title directly.
这篇关于Swiftui:如何在导航标题上添加辅助功能标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!