Skip to content

Instantly share code, notes, and snippets.

@hmlongco
Last active March 17, 2021 12:16
Show Gist options
  • Save hmlongco/5f8fa6fb62fa363c3a87c403dcf15eab to your computer and use it in GitHub Desktop.
Save hmlongco/5f8fa6fb62fa363c3a87c403dcf15eab to your computer and use it in GitHub Desktop.
A11yModifierExample
struct A11yModifier: ViewModifier {
///A label that is visible to UI tests AND VoiceOver
let label: String?
///An identifier that is visible to UI tests NOT VoicOver
let identifier: String?
///The required function that returns our View with the necessary accessibility modifiers
func body(content: Content) -> some View {
content
.conditionalModifier(label != nil) {
$0.accessibility(label: Text(label!))
}
.conditionalModifier(identifier != nil) {
$0.accessibility(identifier: identifier!)
}
}
}
extension View {
@ViewBuilder
func conditionalModifier<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
if condition {
transform(self)
} else {
self
}
}
}
extension View {
///This wrapper simplifies the call so we don't have to use the .modifier(A11yModifier()) syntax
func a11y(label: String? = nil, identifier: String? = nil) -> some View {
self.modifier(A11yModifier(label: label, identifier: identifier))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment