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.
SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.