Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add Custom Accessibility Actions to SwiftUI Views
Written by Team Kodeco

Accessibility in apps is crucial in delivering an inclusive user experience. One accessibility feature that SwiftUI offers is the ability to add custom actions to any view, which can be invoked via assistive technologies like VoiceOver.

A typical use case is to navigate between pages of content. You might implement a simple page control with buttons to go to the next or previous page. However, this can be enhanced with accessibility in mind.

Consider the following SwiftUI code:

struct ContentView: View {
  @State private var currentPage = 1

  var body: some View {
    VStack {
      Text("Page \(currentPage)")
        .font(.largeTitle)
        .padding()

      HStack {
        Button(action: { currentPage = max(currentPage - 1, 1) }) {
          Image(systemName: "arrow.left")
        }

        Spacer()

        Button(action: { currentPage = min(currentPage + 1, 5) }) {
          Image(systemName: "arrow.right")
        }
      }
      .font(.largeTitle)
      .padding()
    }
    .accessibilityElement(children: .ignore)
    .accessibilityLabel(Text("Page control"))
    .accessibilityValue(Text("Page \(currentPage)"))
    .accessibilityAdjustableAction { direction in
      switch direction {
      case .increment:
        currentPage = min(currentPage + 1, 5)
      case .decrement:
        currentPage = max(currentPage - 1, 1)
      @unknown default:
        break
      }
    }
  }
}

Here’s what your preview should look like:

Custom accessibility actions in a SwiftUI view.
Custom accessibility actions in a SwiftUI view.

In this SwiftUI view, you have a simple page control that lets users navigate between five different pages. However, this interface can be simplified for VoiceOver users.

By setting .accessibilityElement(children: .ignore) on the parent VStack, you tell VoiceOver to treat the entire view as a single accessible element.

You then add an accessibilityLabel to describe the control and an accessibilityValue to inform the user of the current page.

Finally, by using the .accessibilityAdjustableAction modifier, you provide a way for VoiceOver users to change the page by using swipe up or down gestures.

This makes the page control easier to navigate for VoiceOver users, and is a demonstration of how custom accessibility actions can significantly improve the user experience of those using assistive technologies. As developers, we should always consider accessibility when building our user interfaces.

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.