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

前端 未结 3 1812
小鲜肉
小鲜肉 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:04

    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)
    

    idea from Custom "Pressed" UIBarButtonItem Backgrounds

提交回复
热议问题