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 setOn method:
[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 for ValueChanged event:
[mySwitch addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventValueChanged];
[mySwitch addTarget:self action:@selector(myMethod:) forControlEvents:UIControlEventValueChanged];
Thanks! exactly what i wanted.
if i may ask, whats the difference between ‘action:@selector(myMethod)’ and ‘action:@selector(myMethod:)’, what does ‘:’ do?
Cheers
when you add colon (:), the method received the reference to the object that called this method
-(void)myMethod:(id)sender {
// sth here
// and you can also send methods to the “sender” – object that called this method, for example valid something, and turn the switch off with uialertview
}
Thank you. It helped a lot.