iOS - How to set a UISwitch programmatically

Suchi picture Suchi · Oct 17, 2011 · Viewed 77.5k times · Source

I want to set my UISwitch to on or off programmatically. How would I do that? I am an iOS newbie.

Answer

Andrew_L picture Andrew_L · Oct 17, 2011

If you are using a UISwitch, then as seen in the developer API, the task setOn: animated: should do the trick.

- (void)setOn:(BOOL)on animated:(BOOL)animated

So to set the switch ON in your program, you would use:

Objective-C

[switchName setOn:YES animated:YES];

Swift

switchName.setOn(true, animated: true)