Making the Day Entry Accessible

Apple works hard to make its products accessible for people with disabilities. One of the accessibility features built into iOS is the screen reader VoiceOver. All UIKit controls automatically work with VoiceOver. But sometimes we have to add a few lines of code to make our apps accessible for visually impaired users.

In this section we’ll make the day entry view accessible. Right now VoiceOver reads a duration of 2 hours and 25 minutes as “two h twenty-five m.” We would like it to say “hours” and “minutes” instead. Another problem with the current state of our app is that the duration and the weekday seem to be unrelated for VoiceOver.

To fix the first problem, change the method durationString(from:) such that it looks like the following code. The changed or added lines are highlighted.

»func​ ​durationString​(from duration: ​TimeInterval​,
» forVoiceOver: ​Bool​ = ​false​) -> ​String​ {
»
»if​ duration < 1 {
»return​ ​"no time outside"
» }
 
 let​ formatter = ​DateComponentsFormatter​()
  formatter.allowedUnits = [.hour, .minute]
 
»if​ forVoiceOver {
» formatter.unitsStyle = .full
» } ​else​ {
» formatter.unitsStyle = .abbreviated
» }
 
 return​ formatter.​string​(from: duration) ?? ​""
 }

If the method is called with forVoiceOver: true, the returned string is optimized for VoiceOver users. In this case we also return a string if the duration is zero, because this feels more natural for VoiceOver users.

Next, add the following method to DayEntryView:

 func​ ​voiceOverGroupString​(​for​ duration: ​TimeInterval​) -> ​String​ {
 let​ duration = ​durationString​(from: duration, forVoiceOver: ​true​)
 return​ ​"​​(​duration​)​​ on ​​(​weekday​)​​"
 }

This method creates and returns the string we want to add for VoiceOver users when they select a day entry.

To group the duration and the weekday for VoiceOver, add the following view modifier to the top-level VStack in the body of DayEntryView:

 var​ body: some ​View​ {
 VStack​ {
 // ...
 // views
 // ...
  }
» .​accessibilityElement​(children: .ignore)
» .​accessibility​(label: ​Text​(​voiceOverGroupString​(for: duration)))
 }

The first modifier disables accessibility for the children of the VStack. We do this because we want to provide an accessibility label for the group. The second modifier adds the text that VoiceOver will speak when the user selects this VStack.

This is all we have to do to make this app usable for visually impaired users. But not only for them—many other accessibility features work automatically when VoiceOver works because they use the same underlying information.

The day entry view is now finished. Next we’ll combine several day entry views to show the outside duration of the last seven days.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.30.210