As Apple's document write, UISwitch
's function setOn(on: Bool, animated: Bool)
does not send action. It works fine before iOS 10, but it will send action after I call it in iOS 10. I call it in "ValueChanged" event to force switch back, so I got this event action twice. is it a bug in iOS 10?

- 581
- 5
- 15
-
I add a delay to call `setOn(on: Bool, animated: Bool)`, action does not be called again。 So it can't call this method in action directly in iOS 10? – codiction Sep 20 '16 at 07:02
-
Did you resolved this issue on iOS 10? – lee Oct 12 '16 at 08:22
-
@lee not yet, I add a delay, but it's not a perfect solution cause switch button flash the state. – codiction Oct 14 '16 at 06:48
-
@edison 's answer is right. let check with get main thread on iOS 10 – lee Oct 14 '16 at 08:38
3 Answers
DispatchQueue.main.async {
sender.setOn(flag, animated: animated)
}
it works for me in Xcode 8.
but call UISwitch.setOn(_:animated:)
directly on main thread doesn't work.
Update
thanks to @codiction:
UISwitch.setOn(_:animated:)
can be called direclty on main thread, but can't be called directly in UISwitch ValueChanged action on iOS 10.

- 171
- 5
-
1`UISwitch.setOn(_:animated:)` can be called direclty on main thread but can't be called directly in `UISwitch` ValueChanged action – codiction Sep 29 '16 at 01:46
-
It work as strange thing on iOS 10.Because, default `setOn` call on main thread on iOS 9, but not on iOS 10. – lee Oct 12 '16 at 08:35
The following solution resolves that issue. You should dispatch_async only if trying to call [UISwitch setOn:] within the action callback of that switch itself.
dispatch_async(dispatch_get_main_queue(), ^{
[switch setOn:YES animated:YES];
});

- 81
- 3
I found these solutions to partially work. However, when I used switch.setOn(false, animated: true)
the onTint
color would appear white in the off position. I'm assuming this is a bug but I worked around this by using this:
switch.setOn(false, animated: true)
switch.onTintColor = .clear
Don't forget to reset the onTint
color when you're ready to allow the switch to be toggled on, if applicable.
switch.onTintColor = <your custom color> // Use nil to use the default onTint for UISwitch
Hopefully this helps save someone a little time.

- 429
- 5
- 10