Reputation: 2066
I am trying to toggle between the play button and pause button in swift. I have a bar button item in the toolbar whose identifier is initially set to the play
. I tried to search and found out the following piece of code but it does not work, looks like it works when the bar button is in the navigation bar
self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "TheMethodThatTheButtonShouldCall"), animated: true)
Upvotes: 1
Views: 3650
Reputation: 12383
Implemented your question with the code as below. works in Swift 2. Please note I connected the IBAction outlet to playBtn
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet var sliderVal: UISlider!
@IBOutlet var theToolbar: UIToolbar!
var mySound = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("ColdPlay", ofType: "mp3")
do {
mySound = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))
}
catch{
print("error caught")
}
}
@IBAction func playBtn(sender: UIBarButtonItem) {
let theBarbuttonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "pauseBtn:")
let arrayBarButtonItem = [theBarbuttonItem]
theToolbar.setItems(arrayBarButtonItem, animated: true)
mySound.play()
}
@IBAction func pauseBtn(sender: UIBarButtonItem) {
let theBarbuttonItemB = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "playBtn:")
let arrayBarButtonItemB = [theBarbuttonItemB]
theToolbar.setItems(arrayBarButtonItemB, animated: true)
mySound.pause()
}
}
Upvotes: 0
Reputation: 2337
You need to set items
on UIToolbar
to update toolbar items: call func setItems(_items: [AnyObject]?,animated animated: Bool)
with your new items to update the toolbar's items
Upvotes: 1