In project 11 we built Bookworm, an app that lets users store ratings and descriptions for books they had read, and we also introduced a custom RatingView
UI component that showed star ratings from 1 to 5.
Again, most of the app does well with VoiceOver, but that rating control is a hard fail – it uses a lot of individual buttons to add functionality, which doesn't convey the fact that they are supposed to represent ratings. For example, if I tap one of the stars, VoiceOver reads out to me, “favorite, button, favorite button, favorite button”, etc – it’s really not useful at all.
That in itself is a problem, but it’s extra problematic because our RatingView
is designed to be reusable – it’s the kind of thing you can take from this project and use in a dozen other projects, and that just means you end up polluting many apps with poor accessibility.
We’re going to tackle this one in an unusual way: first with a simpler set of modifiers that do an okay job, but then by seeing how we can use accessibilityAdjustableAction()
to get a more optimal result.
Our initial approach will use two modifiers, each added to the star buttons. First, we need to add one that provides a meaningful label for each star, like this:
.accessibilityLabel("\(number == 1 ? "1 star" : "\(number) stars")")
Now we can make VoiceOver add a second trait, .isSelected
, if the star is already highlighted.
So, add this final modifier beneath the previous two:
.accessibilityAddTraits(number > rating ? [] : [.isSelected])
It only took two small changes, but this improved component is much better than what we had before.
This initial approach works well enough, and it’s certainly the easiest to take because it builds on all the skills you’ve used elsewhere. However, there’s a second approach that I want to look at, because I think it yields a far more useful result – it works more efficiently for folks relying on VoiceOver and other tools.
First, remove the two modifiers we just added, and instead add these four to the HStack
:
.accessibilityElement()
.accessibilityLabel(label)
.accessibilityValue(rating == 1 ? "1 star" : "\(rating) stars")
.accessibilityAdjustableAction { direction in
switch direction {
case .increment:
if rating < maximumRating { rating += 1 }
case .decrement:
if rating > 1 { rating -= 1 }
default:
break
}
}
That groups all its children together, applies the label “Rating”, but then adds a value based on the current stars. It also allows that rating value to be adjusted up or down using swipes, which is much better than trying to work through lots of individual images.
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.