I'm creating a stopwatch in Swift and I want to change the play icon I have selected for a bar button to a pause icon when the button is pressed to start the stopwatch. How do you do this?
How to change the icon of a Bar Button when pressed in Swift?
8.7k views Asked by Faiz At
3
There are 3 answers
0
On
You can not change a UIBarButtonItem
's style during runtime. You must remove the UIBarButtonItem
and then add the UIBarButtonItem
you'd like.
@IBOutlet weak var toolBar: UIToolbar!
var pauseButton = UIBarButtonItem()
var playButton = UIBarButtonItem()
var arrayOfButtons = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
pauseButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "pauseButtonTapped")
playButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "playButtonTapped")
arrayOfButtons = self.toolBar.items!
arrayOfButtons.insert(playButton, atIndex: 0) // change index to wherever you'd like the button
self.toolBar.setItems(arrayOfButtons, animated: false)
}
func playButtonTapped() {
arrayOfButtons = self.toolBar.items!
arrayOfButtons.removeAtIndex(0) // change index to correspond to where your button is
arrayOfButtons.insert(pauseButton, atIndex: 0)
self.toolBar.setItems(arrayOfButtons, animated: false)
}
func pauseButtonTapped() {
arrayOfButtons = self.toolBar.items!
arrayOfButtons.removeAtIndex(0) // change index to correspond to where your button is
arrayOfButtons.insert(playButton, atIndex: 0)
self.toolBar.setItems(arrayOfButtons, animated: false)
}
0
On
I believe that you already found a solution for your question, but I'll leave this in case anyone still needs it.
UIBarButtonItem
is not a UIControl
, however you can initialise it with a custom view, i.e. a custom UIButton
programmatically as follows:
let playButton = UIButton(frame: CGRectMake(0, 0, 30, 30))
playButton.addTarget(self, action: "togglePlay:", forControlEvents: .TouchUpInside)
playButton.setImage(UIImage(named: "play-active"), forState: .Normal)
playButton.setImage(UIImage(named: "play-inactive"), forState: .Selected)
let rightButton = UIBarButtonItem(customView: playButton)
self.navigationItem.setRightBarButtonItems([rightButton], animated: true)
For Swift 3
This is how I did it in Swift 3:
For Swift 4
var favoritesBarButtonOn: UIBarButtonItem! var favoritesBarButtonOFF: UIBarButtonItem!