iOS - How to set a UISwitch programmatically

Objective CIos

Objective C Problem Overview


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

Objective C Solutions


Solution 1 - Objective C

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)

Solution 2 - Objective C

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

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

Solution 3 - Objective C

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";
    }                

Solution 4 - Objective C

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];

Solution 5 - Objective C

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];   
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSuchiView Question on Stackoverflow
Solution 1 - Objective CAndrew_LView Answer on Stackoverflow
Solution 2 - Objective CNWCoderView Answer on Stackoverflow
Solution 3 - Objective CAnand Kr. AvasthiView Answer on Stackoverflow
Solution 4 - Objective CMike CritchleyView Answer on Stackoverflow
Solution 5 - Objective CAcharya RonakView Answer on Stackoverflow