Swift: change Bar Button Item in code

11,204

Unfortunately you can't change the identifier so you have to set the whole bar button item. You have to do the following:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: "startAlarm:")

To make it nicer you can define an array of UIBarButtonSystemItems and an index like so:

let myArray = [UIBarButtonSystemItem.Start, UIBarButtonSystemItem.Stop]
var index = 0

Then you can do:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: myArray[++index % myArray.count], target: self, action: "startAlarm:")

By the way, remember to use non-capitalized function and variable names ;)

Share:
11,204

Related videos on Youtube

lascoff
Author by

lascoff

Updated on August 21, 2022

Comments

  • lascoff
    lascoff over 1 year

    I am using swift. I have a Bar Button Item that I would like to change the Identifier from Play to Stop in code. Is this possible and how do you do It?

    @IBOutlet var StartStopButton: UIBarButtonItem!
    
    
    @IBAction func StartAlarm(sender: AnyObject) {
    
        onOffIndicator.hidden = false
        StartStopButton.Identifier = ?????
    
    }