Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Localize Accessibility Labels & Hints in SwiftUI
Written by Team Kodeco

Creating an app that is accessible to all users regardless of their abilities is a crucial aspect of modern app development. Among other things, this includes providing clear labels and hints for UI elements to support technologies like Apple’s VoiceOver screen reader. SwiftUI makes this task easier with built-in modifiers for accessibility labels and hints that can be localized for various languages.

In SwiftUI, you can use the accessibilityLabel and accessibilityHint modifiers on any view. Both of these take LocalizedStringKey as their argument, which allows for easy localization.

Note: To follow along with this example, make sure your project includes a Localizable.strings group with Arabic and English localizations. See the chapter “Create a Localized String in SwiftUI” for more information.

Let’s consider an example to illustrate this:

struct ContentView: View {
  @State private var selection = 0

  var body: some View {
    Picker(selection: $selection, label: Text("Picker")) {
      Text("Option 1").tag(0)
      Text("Option 2").tag(1)
      Text("Option 3").tag(2)
    }
    .accessibilityLabel(Text("Selection Picker", comment: "Accessibility label for picker"))
    .accessibilityHint(Text("Select an option", comment: "Accessibility hint for picker"))
  }
}

Add the following to your English localization file:

"Selection Picker" = "Selection Picker";
"Select an option" = "Select an option";

and the following to your Arabic localization file:

"Selection Picker" = "منتقي التحديد";
"Select an option" = "حدد اختيارا";

Here’s what your preview should look like:

Localize accessibility labels and hints in SwiftUI.
Localize accessibility labels and hints in SwiftUI.

In the ContentView, you have a Picker with three options. You use the accessibilityLabel modifier to provide a descriptive label for the picker, “Selection Picker”. This label will be read aloud to users using accessibility features like VoiceOver. The accessibilityHint modifier is used to provide additional instructions, “Select an option”. Users whose device language is set to Arabic will hear these labels and hints in Arabic, not English, since you took the time to prove appropriate localization.

By localizing accessibility labels and hints, you ensure that your app’s accessibility features are tailored to the user’s language settings, further enhancing the app’s usability for a broader audience. It’s a best practice to always provide localized accessibility features as part of your localization workflow, to ensure your app is as accessible and user-friendly as possible in all supported languages.

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.