Iphone Tutorials UI Switch Control

Iphone Tutorials UI Switch Control 
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.

01@interface SwitchDemoViewController : UIViewController {
02    UILabel *switchLabel;
03    UISwitch *toggleSwitch;
06@property (nonatomic,retain) IBOutlet UILabel *switchLabel;
07@property (nonatomic,retain) IBOutlet UISwitch *toggleSwitch;
09-(IBAction) switchValueChanged;
10-(IBAction) toggleButtonPressed;
11 @end
Put the following code in “SwitchDemoViewController.m” file.
01@implementation SwitchDemoViewController
02@synthesize switchLabel;
03@synthesize toggleSwitch;
05- (void)dealloc {
06  [switchLabel release];
07  [toggleSwitch release];
08  [super dealloc];
11-(IBAction) switchValueChanged{
12  if (toggleSwitch.on) { switchLabel.text = @"Enabled"; }
13  else { switchLabel.text = @"Disabled";}
16-(IBAction) toggleButtonPressed{
17  if(toggleSwitch.on){
18    [toggleSwitch setOn:NO animated:YES];
19  }
20  else{
21    [toggleSwitch setOn:YES animated:YES];
23  }
26 @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”.
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 from cinterviews.com 


1 comment:

DVD Replication said...

I am not an iphone user yet but i was thinking about to purchase my iphone. Your post 'll definitely help me to some instinct. Its really a very nice tutorial for me. Thanks for sharing such a great review.

Top Blogs