Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Navigate with Accessibility Rotors in SwiftUI
Written by Team Kodeco

Accessibility rotors are powerful tools that assist users in navigating through the elements of a user interface. This is especially useful for individuals who rely on VoiceOver and other assistive technologies. SwiftUI provides a host of methods that allow developers to create and customize accessibility rotors.

In this entry, you will delve into creating an accessibility rotor for a list of items. This would enable users to quickly navigate through the list by rotating two fingers on the screen, a gesture that VoiceOver users are familiar with.

Imagine you have a simple list of fruit names that we display in a SwiftUI List. You will create an accessibility rotor that will aid in quickly navigating this list.

struct Fruit: Identifiable, Hashable {
  var id: String { name }
  let name: String
}

struct ContentView: View {
  let fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"].map(Fruit.init)

  var body: some View {
    List(fruits, id: \.self) { fruit in
      Text(fruit.name)
    }
    .accessibilityRotor("Fruits", entries: fruits, entryLabel: \.name)
  }
}

Here’s what your preview should look like:

Accessibility rotor in a SwiftUI view.
Accessibility rotor in a SwiftUI view.

In the example above, you have a List view that displays the names of different fruits. You create an accessibility rotor by using the accessibilityRotor modifier on the List view. You pass in a user-visible label for the rotor (“Fruits”) and the entries for the rotor (the fruits array). The entryLabel argument is a key path to a String property on the entry model that provides a label for each entry. You use the key path \.name.

When a VoiceOver user uses the rotor gesture on this list, they will be able to select “Fruits” from the rotor options and then swipe up and down to navigate between the different fruits.

Creating and customizing accessibility rotors are a crucial step in making your SwiftUI apps more accessible. By understanding your users’ needs and tailoring the accessibility features of your app to meet these needs, you ensure that your app can be used and appreciated by everyone.

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.