iOS - How to set a UISwitch programmatically

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)

UISwitches have a property called "on" that should be set.

Are you talking about an iOS app or a mobile web site?


Use this code to solve on/off state problem in switch in iOS

- (IBAction)btnSwitched:(id)sender {
    UISwitch *switchObject = (UISwitch *)sender;
    if(switchObject.isOn){
        self.lblShow.text=@"Switch State is Disabled";
    }else{
        self.lblShow.text=@"Switch State is Enabled";
    }                

I also use the setOn:animated: for this and it works fine. This is the code I use in an app's viewDidLoad to toggle a UISwitch in code so that it loads preset.

// Check the status of the autoPlaySetting
BOOL autoPlayOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoPlay"];

[self.autoplaySwitch setOn:autoPlayOn animated:NO];

ViewController.h

- (IBAction)switchAction:(id)sender;
@property (strong, nonatomic) IBOutlet UILabel *lbl;

ViewController.m

- (IBAction)switchAction:(id)sender {

    UISwitch *mySwitch = (UISwitch *)sender;

    if ([mySwitch isOn]) {
        self.lbl.backgroundColor = [UIColor redColor];
    } else {
        self.lbl.backgroundColor = [UIColor blueColor];   
    }
}