UIBarButton 没有改变

UIBarButton not changing

@IBOutlet weak var playStopButton: UIBarButtonItem!
var playStopArray = [UIBarButtonSystemItem.Pause, UIBarButtonSystemItem.Play]
var index = 0

@IBOutlet weak var image: UIImageView!
@IBAction func playButton(sender: UIBarButtonItem) {
    println("pressed")
    playStopButton = UIBarButtonItem(barButtonSystemItem: playStopArray[index], target: self, action: "startMusic:")
    println("here")
    if index == 0 {
        index = 1
    }
    else {
        index = 0
    }
}
func startMusic() {
    println("test")
}

我希望栏按钮更改为暂停符号,但没有成功。它同时打印 "pressed" 和 "here" 但 "test" 不起作用。为什么图像没有变化?

你的做法是错误的。

在下一行中,
playStopButton = UIBarButtonItem(barButtonSystemItem: playStopArray[index], target: self, action: "startMusic:")
您实际上是在创建 UIBarButtonItem 的新实例。该按钮实际上并未添加到视图中。而不是通过 Interface Builder 添加 UIBarButtonItem。您可以以编程方式创建它。

阅读此问题了解更多信息。 toggle between UIBarButtonSystemItemPlay and UIBarButtonSystemItemPause

var playButton:UIBarButtonItem!
var pauseButton:UIBarButtonItem!

func setup()
{
    playButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "startMusic:")
    pauseButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "stopMusic:")
}

func startMusic:(button : UIBarButtonItem)
{
     self.navigationItem.rightBarButtonItem = pauseButton // Switch to pause.
     //Other code.
}
func stopMusic:(button : UIBarButtonItem)
{
    self.navigationItem.rightBarButtonItem = playButton// Switch to play.
    //Other code.
}

这是我在 Swift

中的方法
func configureBars() {
  isPlaying = false
  // UIToolbar
  let pickBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Search,
    target: self,
    action: "pickSong")
  let playBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Play,
    target: self,
    action: "playPause")
  let pauseBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Pause,
    target: self,
    action: "playPause")
  let leftFlexBBI = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace,
    target: nil,
    action: nil)
  let rightFlexBBI = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace,
    target: nil,
    action: nil)
  playItems = [pickBarButtonItem, leftFlexBBI, playBarButtonItem, rightFlexBBI]
  pauseItems = [pickBarButtonItem, leftFlexBBI, pauseBarButtonItem, rightFlexBBI]

  toolbar.items = playItems
}

访问http://www.raywenderlich.com/36475/how-to-make-a-music-visualizer-in-ios 或者你可以查看我的 Github https://github.com/Charles-Hsu/MusicVisualizer