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:
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.