Change BarButtonItem icon on click

1k Views Asked by At

I'm trying to create a counter. The idea is quite simple, you click on "play" button and once you click it should disappear and become a "pause" icon, which would trigger a different action.

I thought setting a var for counter status and changing the icon (with only one button) would do the trick but I don't have a clue how can I set the button image for "pause" or any other that appears in the drop down menu when you are creating it from the storyboard panel.

Here the code:

@IBOutlet weak var playButton: UIBarButtonItem!
var timer = NSTimer()
var currentStatus = "stopped"


@IBAction func playAction(sender: AnyObject) {
    if (currentStatus == "stopped"){
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("increaseTimer"), userInfo: nil, repeats: true)
        currentStatus = "running"
        // change button icon (playButton) to Stop
    }
    else {
        currentStatus = "stopped"
        timer.invalidate()
       // change button icon (playButton) to Play
    }

}
2

There are 2 best solutions below

0
On

You can set the button style with array like this:

   func addCustomNavigationItemAtLeftAndRightSide(leftButtonItems:[UIBarButtonItem], rightButtonItems:[UIBarButtonItem]) {

    self.navigationItem.leftBarButtonItems = leftButtonItems
    self.navigationItem.rightBarButtonItems = rightButtonItems
 }

You can use with style like this:

  let leftButtonItem = UIBarButtonItem(image: UIImage(named: "ic_top_back"), style: .Plain, target: self, action: "onBackButtonClicked:")
  addCustomNavigationItemAtLeftAndRightSide([leftButtonItem], rightButtonItems: [])
3
On

You can set the button style like this:

//setButton to play
yourBarButtonItem = UIBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "TheMethodThatTheButtonShouldCall"), animated: true)
//setButton to stop
yourBarButtonItem = UIBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: "TheMethodThatTheButtonShouldCall"), animated: true)