我想在UIToolbar
添加播放/暂停类型按钮,但我不确定如何在代码中访问该按钮。我试图为按钮添加一个插座并以这种方式进行更改,但它没有改变这种方式,所以我显然没有正确地做到这一点。
@IBOutlet weak var playPauseButton: UIBarButtonItem!
func toggleButton() {
playPauseButton = UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: "stop:")
}
编辑:我提出的解决方案如下:
(感谢wltrup指出我正确的方向!)
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)
}
或者,使用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)
}
答案 0 :(得分:2)
您需要直接更新工具栏的items
属性(但不是动画版)或使用setItems:animated:
方法。请查看Configuring Toolbar Items下的UIToolbar
文档。