Search code examples
iosuiswitch

programmatically toggle UISwitch, prevent IBAction function


I have a UISwitch, when it is toggled, the IBAction is triggered:

@IBAction func mySwitchToggled( switch_: UISwitch ) {
        ...
}

So, when user toggle the switch, the above function is invoked.

At some point, I also need to toggle the switch programmatically:

mySwitch.setOn(false, animated: false) //It triggers the IBAction function

The above code triggers the IBAction function.

For my special requirement, I need to have the IBAction function being triggered when user toggled the switch but when programmatically toggle the switch, I don't want the IBAction function get triggered.

How to programmatically toggle my switch without triggering the IBAction function?


Solution

  • Please find below, Here swcValueChanged is Value Changed function and it will call only when user toggle the switch.

    @IBAction func swcValueChanged(_ sender: Any) {
        print("Switch value changed")
    }
    

    Here on button tap event, above function will not call.

    @IBAction func btnTapped(_ sender: Any) {
        swcTemp.setOn(!swcTemp.isOn, animated: true)
    }