Tracking a UIBarButtonItem selected state?

romaonthego picture romaonthego · Jan 7, 2014 · Viewed 7.4k times · Source

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

Answer

Jeffrey Sun picture Jeffrey Sun · Oct 26, 2014

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)