UIBarButton没有变化

时间:2015-01-08 00:54:09

标签: swift uibarbuttonitem uibarbuttonsystemitem

@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")
}

我希望条形按钮更改为暂停符号,但没有运气。它会打印"按下"和"在这里"但是"测试"不起作用。为什么图像没有变化?

2 个答案:

答案 0 :(得分:3)

你的做法是错误的。

在以下行中,
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.
}

答案 1 :(得分:2)

这是我在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