UISwitch is one of the simplest structure of UIKit. To create it programmatically, code:
UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(50, 100, 0, 0)];
To add it to your view you should use this code:
[self.view addSubview:mySwitch];
Be default switch is set to Off. You are able to change it’s state programmaticaly using setOnmethod:
[mySwitch setOn:YES animated:YES];
To switch it back to Off use:
[mySwitch setOn:NO animated:YES];
In both above cases UISwitch changes it state with animation (animated:YES), use animated:NO to change state without animation.
To check UISwitch current state use on property, example:
if (mySwitch.on) NSLog(@"switch state: on"); else NSLog(@"switch state: off");
To prevent changing the UISwitch state set the enabled property to NO:
mySwitch.enabled = NO; // or YES to reenable it
As I said before UISwitch is very simple structure – any action – touching it causes UISwitch to change it’s state, so to call any method by changing the UISwitch you have to add a target forValueChanged event:
[mySwitch addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventValueChanged];
[mySwitch addTarget:self action:@selector(myMethod:) forControlEvents:UIControlEventValueChanged];