Posts Tagged ‘UISwitch’

Creating programmatically a switch (UISwitch)

May 8th, 2009

UISwitch is one of the simplest structure of UIKit. To create it programmatically, code:

	UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(50, 100, 0, 0)];
Above line allocates an UISwitch and sets its frame. UISwitch has fixed dimensions (about 95 px long, 27px high), so you have to set the coordinates for top-left corner. Width and height are ignored, you can’t make switch smaller or bigger by changing the frame.

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];
or
	[mySwitch addTarget:self action:@selector(myMethod:) forControlEvents:UIControlEventValueChanged];
If you need a id to mySwitch object.
That’s all about UISwitch. More can be found in UISwitch Class Reference in documentation.