Swift - Toggle UIButton title when selected

20,083

Solution 1

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)
            }
        }
    }

Solution 2

Updated for Swift 3

lazy var toggleBT: UIButton = {

    let button = UIButton()
    button.frame = CGRect(x: 40, y: 100, width: 200, height: 40)
    button.backgroundColor = .orange
    button.isSelected = false   // optional(because by default sender.isSelected is false)
    button.setTitle("OFF", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.titleLabel?.font = .boldSystemFont(ofSize: 14)
    button.addTarget(self, action: #selector(handleToggleBT), for: .touchUpInside)
    return button
}()

func handleToggleBT(sender: UIButton) {

    sender.isSelected = !sender.isSelected

    if sender.isSelected {

        print(sender.isSelected)
        toggleBT.setTitle("ON", for: .normal)
    }

    else {

        print(sender.isSelected)
        toggleBT.setTitle("OFF", for: .normal)
    }
} // don't forget to add this button as a subView for eg. view.addSubview(toggleBT)

enter image description here

Share:
20,083
Rich Townsend
Author by

Rich Townsend

I'm just getting started writing swift!

Updated on July 09, 2022

Comments

  • Rich Townsend
    Rich Townsend almost 2 years

    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