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.

@interface SwitchDemoViewController : UIViewController { UILabel *switchLabel; UISwitch *toggleSwitch; } @property (nonatomic,retain) IBOutlet UILabel *switchLabel; @property (nonatomic,retain) IBOutlet UISwitch *toggleSwitch; -(IBAction) switchValueChanged; -(IBAction) toggleButtonPressed; @end

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

@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{ if(toggleSwitch.on){ [toggleSwitch setOn:NO animated:YES]; } else{ [toggleSwitch setOn:YES animated:YES]; } } @end

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”.

SwitchDemoViewController.xib



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:

Output 1 for SwitchDemo



Output 2 for SwitchDemo



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