简体   繁体   中英

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

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?

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 .

Hope it clear to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM