Rich Townsend
Rich Townsend

Reputation: 589

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

Upvotes: 3

Views: 26132

Answers (3)

Sahidul Islam
Sahidul Islam

Reputation: 139

Updated code for swift5

@IBAction func check2(_ sender: UIButton) {
        
        sender.isSelected = !sender.isSelected //By default sender.isSelected is false  

        if sender.isSelected {
            sender.setTitle("✓", for: .normal)
            sender.setTitleColor(UIColor.green, for: .normal)
        } else {
            sender.setTitle("x", for: .normal)
            sender.setTitleColor(UIColor.red, for: .normal)
        }
    }

Upvotes: 0

iAj
iAj

Reputation: 3817

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

Upvotes: 10

Josh Homann
Josh Homann

Reputation: 16327

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

Upvotes: 14

Related Questions