Reputation: 42652
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?
Upvotes: 2
Views: 2664
Reputation: 1249
hmmm... intersting. It gets triggered in my project
I don't have enough rep to comment so I post it as a answer going at PPL his answer, did you checked your outlets. Most of the time the storyboard keeps the connection to your other IB action which causing them to trigger both. (removing existing outlets and implementing the value change, should work)
Here is another (some what hacky) solution, by implementing a skip boolean when calling the switch by code:
var skip: Bool = false
@IBAction func mySwitchToggled( switch_: UISwitch ) {
guard !skip else {
skip = false
return
}
// do stuff
}
func someFunc() {
// called it like this
skip = true
mySwitch.setOn(false, animated: false)
}
Upvotes: 4
Reputation: 6565
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)
}
Upvotes: 3