In Swift we can use accessibilityElements
for setting accessibility elements of UIview and automationElements
for setting automation elements whose accessibility identifiers can be used in your UITests. How can we achieve this in SwiftUI?
For example, I want to hide an image from Voiceover and accessible for automation:
Image(.close).resizable()
.frame(width: 10, height: 10)
.accessibilityHidden(true)
.accessibilityIdentifier(identifier: "image")
But I cannot see this accessibilityInspector
You didn't specify whether you're using XCTests UI autionamtion, so I assume you are.
During preparation of your app to launch you can add launch arguments:
func testLaunch() throws {
let app = XCUIApplication()
// Setting up launch arguments that are going to be used when passing environemnt value
app.launchArguments = ["isInUITesting"]
app.launch()
... // the rest of your test
}
Next step would be to define a new environment value:
extension EnvironmentValues {
@Entry var isInUITesting: Bool = false
}
The value should be passed to a hierarchy where you would like to use it, in my case I pass it from app declaration:
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.isInUITesting, ProcessInfo.processInfo.arguments.contains("isInUITesting"))
}
}
}
As you can see I check whether process info's arguments have the argument we passed in the test above(probably better to avoid plain strings, at least static one would help to avoid typos)
The last step is to read the value in the view where you want to hide/show accessibility:
struct ContentView: View {
@Environment(\.isInUITesting) var isInUITesting
var body: some View {
Image(systemName: "gear")
.accessibilityHidden(!isInUITesting)
.accessibilityIdentifier("Main_Image")
}
}