Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add Custom Accessibility Content in SwiftUI Views
Written by Team Kodeco

In developing applications that are accessible to a wide range of users, SwiftUI provides a wealth of features to make this task easier. One such feature is the ability to add custom accessibility content to a view, which can provide users with additional information about the view beyond its label, value and hint.

This information can be particularly helpful for accessibility users who rely on assistive technologies like VoiceOver. Using the accessibilityCustomContent modifier, you can specify additional details that can be read out by VoiceOver.

Note: If you want to try out this example, you can download an archive containing the image here.

Here’s an example of how you might use accessibilityCustomContent in an image view:

struct ContentView: View {
  var body: some View {
    VStack {
      Image("landscape_photo")
        .resizable()
        .scaledToFit()
        .accessibilityLabel(Text("Landscape Photo"))
        .accessibilityCustomContent(
          "detail",
          "A serene landscape photo showing a green meadow under a clear blue sky",
          importance: .high
        )
    }
    .padding()
  }
}

Here’s what your preview should look like, once you’ve added the landscape photo to your project’s asset catalog:

Custom accessibility content in a SwiftUI view.
Custom accessibility content in a SwiftUI view.

In this example, an image view displays a landscape photo. The accessibilityCustomContent modifier adds a detailed description of the photo that VoiceOver can read to the user.

The "detail" parameter is a key used to specify the identifier and label of the additional accessibility information entry. The second parameter is the text value for the additional accessibility information. The importance parameter sets the importance of the information. If the importance is set to .high, VoiceOver will read out the information immediately, whereas if it’s set to .default, the user must explicitly ask for the information.

By leveraging the accessibilityCustomContent modifier, you can provide richer contextual information about your SwiftUI views, making your app more accessible to all users.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.