Search code examples
iosswiftuitoolbar

Swift - UIToolbar item selected state


I have this toolbar in my navigation controller. Now what I am trying to do is when the user selects an item (UIBarButtonItem) in my toolbar, have that item highlighted with a background colour until either the user deselects the item or selects another item. How would I do this?

Here are my selector methods for each item of the toolbar, I connected them via storyboard:

@IBAction func addText(sender: AnyObject) {
        annotationSelected = 3
}

@IBAction func drawCircle(sender: AnyObject) {
    annotationSelected = 1
}

@IBAction func drawRectangle(sender: AnyObject) {
    annotationSelected = 2
}

@IBAction func drawStamp(sender: AnyObject) {
    annotationSelected = 4
}

This is all I have done. Here is a screenshot of my toolbar:

enter image description here

Here is what I got:

@IBOutlet var textToolButton: UIBarButtonItem!

    @IBOutlet var circleToolButton: UIBarButtonItem!

    @IBOutlet var rectangleToolButton: UIBarButtonItem!

    @IBOutlet var stampToolButton: UIBarButtonItem!

then

textToolButton.target = self
        textToolButton.style = .Done
        textToolButton.action = #selector(ViewController.barButtonPressed)

        let selectedBackgroundColor = UIImage(color: .redColor())

        textToolButton.setBackgroundImage(selectedBackgroundColor, forState: UIControlState.Highlighted, style: .Done, barMetrics: UIBarMetrics.Default)

and then the method

func barButtonPressed(sender: UIBarButtonItem) {

        print(sender)
        annotationSelected = sender.tag
    }

background is still not changing color


Solution

  • I find a same question. May be can help you. custom-pressed-uibarbuttonitem-backgrounds

    I find a easy method to do. You can dray a button to the toolBar,and you will see like this.

    And you should change the button's type and Image. storyboard screenshot

    then you should link the button to your viewController.

    @IBOutlet weak var textToolButton: UIButton!
    

    and you can do.

    let selectedBackgroundColor = UIImage(color: .redColor())
    textToolButton.setBackgroundImage(selectedBackgroundColor, forState: .Highlighted)
    

    May be I can help you.