iosswiftuibuttonuicontroluicontrolstate

Swift - Toggle UIButton title when selected


I'm looking to implement a button that can be used as a tickbox and enablers the user to toggle the tickbox in an on/off fashion (unticked/ticked). Currently I've set up my button using the attributes inspector including the 'Title' as "X" and the 'Text Color' is red.

Once loaded the button appears a red "X", once tapped it turns to a green tick.

My question is... how do you enable the button to be tapped again to revert back to the red X (it's original state), an continue in a loop whenever tapped?

    @IBAction func check2(_ sender: UIButton) {
     sender.setTitle("✓", for: .normal)
    sender.setTitleColor(UIColor.green, for: UIControlState.normal)
}

Thank you


Solution

  • Track the state with a variable and update the appearance based on the state:

        class ViewController: UIViewController{
            @IBOutlet weak var button: UIButton!
            var isChecked = true
    
            @IBAction func check2(_ sender: UIButton) {
                isChecked = !isChecked
                if isChecked {
                    sender.setTitle("✓", for: .normal)
                    sender.setTitleColor(.green, for: .normal)
                } else {
                    sender.setTitle("X", for: .normal)
                    sender.setTitleColor(.red, for: .normal)
                }
            }
        }