Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use UIBarButtonSystemItem to change UIBarButtonItem identifier? (Swift)

I want to change the identifier of an UIBarButtonItem with codes from "Play" to "Pause". How can I do that?

Thanks

like image 312
Ahmed Avatar asked Jan 29 '15 10:01

Ahmed


3 Answers

1) init a new button

//change to play
let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "someAction")
navigationBar.topItem.leftBarButtonItem = button

//change to pause
let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "someOtherAction")
navigationBar.topItem.leftBarButtonItem = button

2) Just change the text:

navigationBar.topItem?.leftBarButtonItem?.title = "AnyText"

If you're also having trouble accessing the navigation bar it is probably best to just set some tag to it (I like to use negative tags for specific Views* to make sure 2 views* don't get the same tag). Then you could fx do like this:

let navigationBar = (self.view.viewWithTag(-1) as UINavigationBar)
navigationBar.topItem?.leftBarButtonItem?.title = "AnyText"
like image 137
Þorvaldur Rúnarsson Avatar answered Dec 06 '22 09:12

Þorvaldur Rúnarsson


I use this code to switch Edit mode

@IBAction func editMode(sender: UIBarButtonItem) {
    self.setEditing(!self.isEditing, animated: true)

    let newButton = UIBarButtonItem(barButtonSystemItem: (self.isEditing) ? .done : .edit, target: self, action: #selector(editMode(sender:)))
    self.navigationItem.setLeftBarButton(newButton, animated: true)
}
like image 32
Paulo Bruckmann Avatar answered Dec 06 '22 11:12

Paulo Bruckmann


For a toolbar item, here is the sample code.

var player:AVAudioPlayer = AVAudioPlayer()

@IBOutlet var toolbar: UIToolbar!
@IBOutlet var playPauseButton: UIBarButtonItem!

@IBAction func playPause(sender: AnyObject) {

    if player.playing {

        player.pause()

        playPauseButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "playPause:")

        toolbar.items![0] = playPauseButton //apply for first toolbar item

    } else {

        player.play()

        playPauseButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "playPause:")

        toolbar.items![0] = playPauseButton //apply for first toolbar item


    }

}
like image 27
Arda Ç. Avatar answered Dec 06 '22 11:12

Arda Ç.