Tracking a UIBarButtonItem selected state?
Asked Answered
S

3

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

Southwestward answered 6/1, 2014 at 23:39 Comment(2)
possible duplicate of programmatically highlight UIBarButtonItemObstacle
Check out my answer to basically the same question here: #19321347Oberammergau
C
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)

Caucasoid answered 26/10, 2014 at 20:16 Comment(0)
L
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.

Loria answered 2/7, 2020 at 3:18 Comment(1)
Interesting, but probably not very future safe unfortunately..Hickey
G
0
item.image = UIImage(named: isSelected ? "SelectedImage" : "NormalImage")
Groundage answered 29/7, 2017 at 17:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.