1

I currently have a UIButton that changes from red to green when selected. How can I implement the reverse, so that it goes back to the original state when selected again? Below is my current code:

 @IBAction func button1press(_ sender: AnyObject) {
    (sender as! UIButton).backgroundColor = UIColor.green
    }
Andy Voelker
  • 81
  • 3
  • 10
  • 1
    Unrelated to your question but your code will be easier if you declare `sender` to be `UIButton` instead of `AnyObject`. – rmaddy Feb 09 '17 at 23:14
  • @rmaddy is correct. And if you do, you can tie your actions to anything a UIButton state can be - including selected. –  Feb 09 '17 at 23:37
  • Possible duplicate of [How to know when the button is pressed and canceled Button pressing](http://stackoverflow.com/questions/41947279/how-to-know-when-the-button-is-pressed-and-canceled-button-pressing). This should give you all you need. If not, edit your question and I'm sure we can answer. –  Feb 09 '17 at 23:39

2 Answers2

2

When tapping the button update the selected state, i.e: This way you know which state the button is at.

If you wish to edit other properties, such as text color, font, image etc... you can just use the storyboard "State Config" option, and make different themes for different states (within the IB's limits)

@IBAction func button1press(_ sender: AnyObject) {
    if let button : UIButton = sender as? UIButton
    {
        button.isSelected = !button.isSelected

        if (button.isSelected)
        {
            button.backgroundColor = UIColor.green
        }
        else
        {
            button.backgroundColor = UIColor.red
        }
    }
}
unkgd
  • 671
  • 3
  • 12
0

On each press, check the current background color, and change it to the other one.

@IBAction func button1press(_ sender: UIButton) {
    if let button = sender as? UIButton {
        if button.backgroundColor == UIColor.green {
            button.backgroundColor = UIColor.red
        }
        else if button.backgroundColor == UIColor.red {
            button.backgroundColor = UIColor.green
        }
    }
}
Shades
  • 5,568
  • 7
  • 30
  • 48