我正试图在swift中的播放按钮和暂停按钮之间切换。我在工具栏中有一个条形按钮项,其标识符最初设置为play
。我试图搜索并发现以下code但它不起作用,当条形按钮在导航栏中时它看起来很有效
self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "TheMethodThatTheButtonShouldCall"), animated: true)
答案 0 :(得分:1)
您需要在items
上设置UIToolbar
来更新工具栏项目:使用新项目调用func setItems(_items: [AnyObject]?,animated animated: Bool)
以更新工具栏的商品
答案 1 :(得分:0)
使用以下代码实现您的问题。适用于Swift 2.请注意我将IBAction插座连接到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()
}
}