9

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:

Maps app

or Shuffle All from the Music app:

Music App

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
romaonthego
  • 810
  • 1
  • 8
  • 16
  • possible duplicate of [programmatically highlight UIBarButtonItem](http://stackoverflow.com/questions/8267758/programmatically-highlight-uibarbuttonitem) – nemesis Jan 07 '14 at 02:34
  • Check out my answer to basically the same question here: http://stackoverflow.com/questions/19320847/how-to-set-uibarbuttonitem-selected-or-highlighted-image-or-tint-colours-in-ios – Kevin_TA May 22 '15 at 19:40

3 Answers3

2

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)

Jeffrey Sun
  • 7,789
  • 1
  • 24
  • 17
1

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.

Michael Berk
  • 365
  • 2
  • 16
0
item.image = UIImage(named: isSelected ? "SelectedImage" : "NormalImage")
Moose
  • 2,607
  • 24
  • 23