MegaTron MegaTron - 1 month ago 13
Swift Question

Swift: How to toggle two UI Switches


  • I have two UI Switches


    • When I tap one, I want the other to turn off and vice versa

    • Below I have two switch actions.

    • I've tried to check if switch one is on (which is by default) and if it is when tapped, then turn it off, but if it isn't on, then turn it on.

      @IBAction func switchOnePressed(_ sender: UISwitch) {
      if switchOne.isOn {
      label.text = "UISwitch is ON"
      switchOne.setOn(false, animated: true)
      } else {
      label.text = "UISwitch is OFF"
      switchOne.setOn(true, animated: true)
      }
      }

      @IBAction func switchTwoPressed(_ sender: UISwitch) {}




Any help would be great!

Answer

This simplifies things a lot by reducing the code required. The opposite switch is then set based off the current value of the calling switch.

@IBAction func switchOnePressed(_ sender: UISwitch) {
    label.text = sender.isOn ? "UISwitch is ON" : "UISwitch is OFF"
    switchTwo.setOn(!sender.isOn, animated: true)
}

@IBAction func switchTwoPressed(_ sender: UISwitch) {
    label.text = sender.isOn ? "UISwitch is ON" : "UISwitch is OFF"
    switchOne.setOn(!sender.isOn, animated: true)
}

You do not need to set the value for the calling switch since that should already be handled by the interface interaction.

Also, I don't know what your intention is with the label, but it would be misleading in its current form since it does not indicate what switch is on & off. Perhaps you have unique labels for each one, but that is just speculation on my part.