Reputation: 810
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:
Upvotes: 9
Views: 8361
Reputation: 435
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.
Upvotes: 1
Reputation: 2737
item.image = UIImage(named: isSelected ? "SelectedImage" : "NormalImage")
Upvotes: 0
Reputation: 8049
You can set the background image of the UIBarButtonItem
:
item.setBackgroundImage(UIImage(named: "item-bg.png"), forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
Then when you want to de-select it, set the background image to nil
:
item.setBackgroundImage(nil, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
(You have to create an image file for the background)
Upvotes: 2