Reputation: 8685
I want to add a play/pause type button to a UIToolbar
but I'm unsure how to access the button in code. I've tried to add an outlet for the button and change it that way but it doesn't change this way so I'm obviously not doing it correctly.
@IBOutlet weak var playPauseButton: UIBarButtonItem!
func toggleButton() {
playPauseButton = UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: "stop:")
}
Edit: The solution I came up with was the following:
(Thanks wltrup for pointing me in the right direction!)
var isActive = false
@IBOutlet weak var toolbar: UIToolbar!
@IBAction func playPauseButton(sender: AnyObject) {
if (!isActive) {
play()
swapPlayPauseButton(.Pause)
} else {
pause()
swapPlayPauseButton(.Play)
}
isActive = !isActive
}
func swapPlayPauseButton(barButtonSystemItem: UIBarButtonSystemItem) {
var items = [AnyObject](toolbar.items!)
items[2] = UIBarButtonItem(barButtonSystemItem: barButtonSystemItem, target: self, action: "playPauseButton:")
toolbar.setItems(items, animated: true)
}
Or alternatively, a solution using a property observer suggested by wltrup:
var timer: NSTimer? {
didSet {
isActive = (timer != nil)
if timer == nil {
swapPlayPauseButton(.Play)
} else {
swapPlayPauseButton(.Pause)
}
}
}
@IBAction func playPauseButton(sender: AnyObject) {
if (!isActive) {
play()
} else {
pause()
}
}
func swapPlayPauseButton(barButtonSystemItem: UIBarButtonSystemItem) {
var items = [AnyObject](toolbar.items!)
items[2] = UIBarButtonItem(barButtonSystemItem: barButtonSystemItem, target: self, action: "playPauseButton:")
toolbar.setItems(items, animated: true)
}
Upvotes: 1
Views: 1100
Reputation: 798
You need to update the items
property of the toolbar, either directly (but then it's not animated) or by using the setItems:animated:
method. Take a look at the documentation for UIToolbar
under Configuring Toolbar Items.
Upvotes: 2