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 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)
}
UIBarButtonItem Class Reference