Search code examples
iosswiftxcodeuibuttonbackground-color

How to return button background color to default after second push?


I am working on a app. There is a button. When you push on it its background becomes green. How make it return to default color after pressing it one more time. And green again after next time?

override func viewDidLoad() {
    super.viewDidLoad()

}


@IBAction func keyPressed(_ sender: UIButton) {
    sender.backgroundColor = UIColor.green
    }

Solution

  • You can probably change and check the UIButton's isSelected property for that simple thing, like this:

    @IBAction func keyPressed(_ sender: UIButton) {
        if sender.isSelected {
            sender.backgroundColor = .clear
        } else {
            sender.backgroundColor = .green
        }
        sender.isSelected.toggle()
    }