Coder221 Coder221 - 2 months ago 55
Swift Question

Toggle between select/deselect UIButton

I have a button which I want to change background color and text when tapped(select) and bring it back to its original state when tapped again (deselect). I am able to select it but I am not being able to deselect it. I have researched on SO and I am getting errors in this code in the if-else part

@IBAction func btn1Pressed(_ sender: AnyObject) {
sender.setTitleColor(UIColor.blue, for: UIControlState.normal)
(sender as! UIButton).backgroundColor = UIColor.green

if sender.isSelected {
sender.selected = false
}
else {
sender.selected = true
}
}

Answer

Try this:

@IBAction func btn1Pressed(_ sender: AnyObject) {

    guard let button = sender as? UIButton else { return }

    if !button.isSelected {
        button.isSelected = true
        button.setTitleColor(UIColor.blue, for: UIControlState.normal)
        button.backgroundColor = UIColor.green
    }
    else {
        button.isSelected = false
        button.setTitleColor(UIColor.green, for: UIControlState.normal)
        button.backgroundColor = UIColor.blue
    }
}