@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")
}
I expected the bar button to change to the pause symbol, but with no luck. It prints both "pressed" and "here" but "test" does not work. Why is the image not changing?
Your approach is wrong.
In the following line,
playStopButton = UIBarButtonItem(barButtonSystemItem: playStopArray[index], target: self, action: "startMusic:")
you are actually creating a new instance of UIBarButtonItem
. This button is not actually added into the view. Instead of adding the UIBarButtonItem
through Interface Builder. You can create it programmatically.
Read this question for more information.
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.
}
Here is my approach in 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
}
visit http://www.raywenderlich.com/36475/how-to-make-a-music-visualizer-in-ios
or you can check out my Github https://github.com/Charles-Hsu/MusicVisualizer