ylliX - Online Advertising Network
Conditional SwiftUI Accessibility Labels

Conditional SwiftUI Accessibility Labels


In iOS 18, Apple added an optional isEnabled parameter to many of the accessibility modifiers.

Conditional Accessibility Modifiers (iOS 18)

Apple added the isEnabled parameter to .accessibilityLabel, .accessibilityInputLabels, .accessibilityValue, .accessibilityHint and many other accessibility modifiers. This has the effect of only applying the modifier when the isEnabled parameter is true.

This is useful in situatons where you need to conditionally override the default accessibility behaviour. For example, this labeled content has a button with a system symbol image:

LabeledContent {
    Button {
        toggleFavorite(item)
    } label: {
        Image(systemName: item.favorite ? "star.fill" : "star")
    }
} label: {
    Text(item.name)
}

I’m using the labeled content in a list of items, the button toggling the favorite status of each item:

Three rows in a list of items, red, orange, and yellow. The orange item has a filled star, the others unfilled stars.

The button label provides the default accessibility label for the button action. In this example I’m using the “star” SF symbol which has a default (localized) accessibility label of “favorite”.

That’s great but I’d like to change the label based on favorite status of the item. Favorited items show the filled version of the “star” symbol and I’d like the accessibility label for the button action to be “unfavorite”.

One way is with an accessibility label that is conditional on the favorite status of the item:

Image(systemName: item.favorite ? "star.fill" : "star")
  .accessibilityLabel(item.favorite ? "Favorite" : "Unfavorite")

That works, but in situatons like this where we already have a suitable default label we can use the isEnabled variant of the modifier:

Image(systemName: item.favorite ? "star.fill" : "star")
  .accessibilityLabel("Unfavorite", isEnabled: item.favorite)

It’s a small improvement but I think still useful to avoid having to repeat (and localize) the default label.

Learn More



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *