Search code examples
iosswiftuiswitch

how to use uiswitch for selecting category in swift?


Trying to create an if else statement for a UISwitch. Not exactly sure what goes in the if else statements to check whether the switch is on or off.

@IBAction func selectionLabel(sender: AnyObject) {
    if(<some condition>)
    // do something

    else
      //do something
}

Is this a correct way to use the switch?


Solution

  • The sender is the switch. Check if the switch is on by checking the on property:

    @IBAction func selectionLabel(sender: AnyObject) {
        if let mySwitch = sender as? UISwitch {
            if mySwitch.on {
                // switch is on
            } else {
                // switch is off
            }
        }
    }