How to change the icon of a Bar Button when pressed in Swift?

前端 未结 3 1830
小鲜肉
小鲜肉 2021-02-10 16:23

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

3条回答
  •  我寻月下人不归
    2021-02-10 17:06

    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

提交回复
热议问题