FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

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)

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.

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for iOS devs who want to become complete senior developers — from October 18th to 24th. Learn how to apply iOS app architecture patterns through a series of lectures and practical coding sessions.

Learn more

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

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

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.