Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: change Bar Button Item in code

Tags:

ios

swift

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 = ?????

}
like image 225
lascoff Avatar asked Dec 26 '14 18:12

lascoff


1 Answers

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 ;)

like image 173
borchero Avatar answered Sep 29 '22 11:09

borchero