Is there a way to highlight (i.e., toggle) a UIBarButtonItem without using a custom view?
For example, see 3D button from the Maps app:

or Shuffle All from the Music app:

Is there a way to highlight (i.e., toggle) a UIBarButtonItem without using a custom view?
For example, see 3D button from the Maps app:

or Shuffle All from the Music app:

On
The issue is that wile UIControl has an isSelected property that achieves this goal, UIBarButtonItem doesn't inherit from that, so you can't cast it and set the value. However, there's a strange workaround I discovered. If you set the type for the sender of the button's action as UIControl, it will be treated as a full-blown UIControl, and you can set isSelected.
for example:
@objc func showContentsView(_ sender: UIControl) {
sender.isSelected.toggle()
}
If you need to toggle the state elsewhere, you can have a variable on your View Controller like this:
var selectedControl: UIControl?
Set the value of selectedControl in your action and set it to nil when unselecting it.
You can set the background image of the
UIBarButtonItem:Then when you want to de-select it, set the background image to
nil:(You have to create an image file for the background)