MegaTron
MegaTron

Reputation: 3393

Swift: How to toggle two UI Switches

Any help would be great!

Upvotes: 3

Views: 9749

Answers (1)

CodeBender
CodeBender

Reputation: 36620

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.

Upvotes: 6

Related Questions