BLACK FRIDAY: Save 50% on all books and bundles! >>

Reading the value of controls

Paul Hudson    @twostraws   

By default SwiftUI provides VoiceOver readouts for its user interface controls, and although these are often good sometimes they just don’t fit with what you need.

A good example of this is the Slider control, which VoiceOver reads out as a series of percentages. If you’re using percentages then this makes sense, but if you aren’t then you can override the value VoiceOver reads out by using the accessibility(value:) modifier to provide some alternative text.

To demonstrate this, here’s a slider that asks users to enter an estimate between 0 and 50:

@State private var estimate = 25.0

var body: some View {
    Slider(value: $estimate, in: 0...50)
        .padding()
}

If you run that back you’ll hear that VoiceOver reads values as percentages, which makes no sense. To fix this, we can use the accessibility(value:) modifier to provide custom text, like this:

.accessibility(value: Text("\(Int(estimate))"))

This is particularly important in places where SwiftUI doesn’t do a great job of updating the UI as values change. For example, right now it doesn’t read out values when a stepper changes unless you specifically attach your own .accessibility(value:) modifier. I’m hoping this is just a bug that will be fixed in the near future, but you can find out yourself with this kind of code:

@State private var rating = 3

var body: some View {
    Stepper("Rate our service: \(rating)/5", value: $rating, in: 1...5)
}

When that runs, at least right now, you can select the stepper and swipe up or down to change the value, but VoiceOver won’t read out the values as they change. We can fix this by adding a custom read out for the values, like this:

.accessibility(value: Text("\(rating) out of 5"))

Even after Apple fixes this bug (and I’m sure they will!), being able to control the precise VoiceOver read out is really important.

Save 50% in my Black Friday sale.

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

Link copied to your pasteboard.