Toggling iOS Bar Button identifier (Play/Pause) in Swift

612 Views Asked by At

I know similar questions have been asked and answered in the past. However, I seem to have trouble with executing a simple act of toggling the left bar button from Play to Pause.

Here is my code:

@IBAction func toggleButton(sender: AnyObject) {
    self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "someFakeAction"), animated: true)
}

func someFakeAction() {
    println("Button pressed")
}

When I tap the Play button, there is a quick fading animation and then the Play button returns. The function someFakeAction is not called. What am I doing wrong?

1

There are 1 best solutions below

0
Rashad On

Try this:

  1. Declare UIBarButtonItem globally so that you can access it later. lets call it playPauseButton

  2. Declare a boolean variable globally for keeping track if it is playing or paused, lets call it isPlaying.

  3. From viewDidLoad init isPlaying = true, and playPauseButton with action pauseIt and set it as leftBarButtonItem.

  4. if button is pressed in pauseIt method init isPlaying = false, initialize playPauseButton with a action playIt and set it to leftBarButtonItem.

  5. in playIt set isPlaying = true again and init the playPauseButton with action pauseIt.