Switch in an iphone application is very similar to its electronic counterpart in its working. By default it is set to OFF. You can change its value manually or programmatically (as you prefer). When the switch is pressed, it toggles with animation and changes its state from ON to OFF or OFF to ON. For eg. It can be used to mute or unmute volume.

In this tutorial, we will change the value of the switch manually and programmatically. So lets get started.

Step 1: Start Xcode and create a view based application with name “SegmentedControlDemo”.

Step 2: Put the following code in “SwitchDemoViewController.h” file.

[objc highlight="2,3,6,7,9,10"]
@interface SwitchDemoViewController : UIViewController {
		UILabel *switchLabel;
		UISwitch *toggleSwitch;

@property (nonatomic,retain) IBOutlet UILabel *switchLabel;
@property (nonatomic,retain) IBOutlet UISwitch *toggleSwitch;

-(IBAction) switchValueChanged;
-(IBAction) toggleButtonPressed;


Put the following code in “SwitchDemoViewController.m” file.

[objc highlight="2,3,6,7,11,12,13,14,16,17,18,19,20,21,22,23,24,25"]
@implementation SwitchDemoViewController
@synthesize switchLabel;
@synthesize toggleSwitch;

- (void)dealloc {
	[switchLabel release];
	[toggleSwitch release];
	[super dealloc];

-(IBAction) switchValueChanged{
	if (toggleSwitch.on) { switchLabel.text = @"Enabled"; }
	else { switchLabel.text = @"Disabled";}

-(IBAction) toggleButtonPressed{
		[toggleSwitch setOn:NO animated:YES];
		[toggleSwitch setOn:YES animated:YES];




switchValueChanged method:
In this method, we have monitored the value of the switch. If it is on, we set the text of the label to “Enabled” and if it is off, we set it to “Disabled”.

toggleButtonPressed method:
Here, if the switch value is on, we set it to off using the setOn: animated: method. And vice versa.

Step 3: Save(command+s) the project. Open the “SwitchDemoViewController.xib” file from Resources folder. Add a label,switch and a button to the view.Name the button “toggle”.
iPhone Switch Control: UISwitch Control Tutorial

Step 4: Now go to Connections Inspector(command+2) for File’s Owner. Connect switchLabel to label, toggleSwitch to switch, switchValueChanged method to “Value changed” event of the switch and toggleButtonPressed method to “Touch Up Inside” event of the button in the view.

Step 5: Save,build and run the project. When you toggle the switch, the text of the label will change and when you press the toggle button, the state of the switch will change.

You can download the source code here.

Output 1 for SwitchDemo
iPhone Switch Control: UISwitch Control Tutorial
Output 2 for SwitchDemo
iPhone Switch Control: UISwitch Control Tutorial

Thats the end of the tutorial folks. You are now ready to dabble with switches.