It is possible to embed icons within text using NSTextAttachment and NSAttributedString. If you do, please remember to override the accessibility label, otherwise VoiceOver will announce it as "Attachment.png File".

If you assign an attributed string to the attributed text property in a label, and the attributed string contains an nstextattachment that is an image, you need to override the accessibility label of the label. In the example, if you don't do it, VoiceOver would say:

Example code in the image:

let magnifyingGlassIcon = UIImage(systemName: "magnifyingglass")!
let searchButton = UIButton()
let searchTutorialLabel = UILabel()
searchButton.accessibilityLabel = "search"

let textAttachment = NSTextAttachment(image: magnifyingGlassIcon)
let string = "Select the  button to find elements in the list"
let attributedString = NSMutableAttributedString(string: string)
let attributedStringIcon = NSAttributedString(attachment: textAttachment)
let iconPlaceholderRange = attributedString.string.range(of: "")!
let iconRange = NSRange(iconPlaceholderRange, in: attributedString.string)

attributedString.replaceCharacters(in: iconRange, with: attributedStringIcon)
searchTutorialLabel.attributedText = attributedString


searchTutorialLabel.accessibilityLabel = string.replacingCharacters(in: iconPlaceholderRange,
                                                                    with: searchButton.accessibilityLabel!)

You may also find interesting...

Do you know when a UI element is greyed out to show that it is disabled? Yes, there is an accessibility trait for that too: .notEnabled. VoiceOver will say “dimmed” after its accessibility label and Voice Control and Switch Control will skip it.

Test manually. Familiarise yourself with different assistive technologies. I find it useful to start with VoiceOver but check out Voice Control, Full Keyboard Access, and others... Remove friction, configuring shortcuts can help. Merry Christmas!

A common example where you need to manually configure the button accessibility trait is for some table/collection view cells. These tend to be “buttons” that perform an action, like playing music, or bring the user to a different screen.

Created in Swift with Ignite.

Supporting Swift for Swifts