Feindpak Feindpak - 28 days ago 10
Swift Question

How can i change the State of a checkbox in swift without clicking it?

For example, i have two checkboxes, and my goal is it if checkbox 1 is checked that checkbox 2 is checked too. and if checkbox 1 is unchecked that checkbox 2 is unchecked too. How can i change the state of a checkbox without clicking it?

Answer

Connect your checkboxes with the view controller like that:

class ViewController: UIViewController {

  @IBOutlet weak var checkBox1: UISwitch!      
  @IBOutlet weak var checkBox2: UISwitch!

}

Then add an IBAction for your first checkbox to the view controller with using an if else to switch also the second checkbox, like that:

class ViewController: UIViewController {

  @IBOutlet weak var checkBox1: UISwitch!
  @IBOutlet weak var checkBox2: UISwitch!

  @IBAction func checkBox1Pressed(_ sender: UISwitch) {
    // using if else
    if checkBox1.isOn {
      checkBox2.setOn(true, animated: true)
    } else {
      checkBox2.setOn(false, animated: true)
    }
  }
}

or using the ternary operator, like that:

class ViewController: UIViewController {

  @IBOutlet weak var checkBox1: UISwitch!
  @IBOutlet weak var checkBox2: UISwitch!

  @IBAction func checkBox1Pressed(_ sender: UISwitch) {
    // or using ternary operator
    checkBox1.isOn ? checkBox2.setOn(true, animated: true) : checkBox2.setOn(false, animated: true)
  }
}

Result:

enter image description here

If you don't use UISwitch, please update your question with your current code

Comments