Setting UIAccessibilityTraitImage (page 442)

For anyone who’s still working through this version of the book and came across the section of code for setting the UIAccessibilityTraits to UIAccessibilityTraitImage:

override var accessibilityTraits: UIAccessibilityTraits { 
     get { 
          return super.accessibilityTraits | UIAccessibilityTraitImage 
     } 
     set { 
          // Ignore attempts to set 
     }
}

I couldn’t personally get the code to work, even after going down Xcode’s autocorrection chain of horror to use raw values:

override var accessibilityTraits: UIAccessibilityTraits {
     get { 
          return UIAccessibilityTraits(rawValue: super.accessibilityTraits.rawValue | UIAccessibilityTraits.image.rawValue) }
    set { /* ignore attempts to set accessibility label */ }
}

While the raw value route did end up reading off the images, no one wants to tap an image and hear the raw value read out to them.

I instead managed to get it to work by enabling the Accessibility checkbox in the Identity Inspector of the Image View itself in the PhotoCollectionViewCell, keeping the two previous pieces of code for the isAccessibilityElement and accessibilityLabel overrides.

    override var isAccessibilityElement: Bool {
        get { return true }
        set { super.isAccessibilityElement = newValue }
    }
    
    override var accessibilityLabel: String? {
        get { return photoDescription }
        set { /* ignore attempts to set accessibility label */ }
    }

I will add that if the downloaded images have a nonsensical title or no title at all, then a nonsensical title (image_433345_edit_v2) will be read off, but there isn’t much we can do there without some more coding for all those weird titles I suppose.