Introduction
In this article I will create a Single view application. Here I use a Switch, Button and label from outlet. When we Tap on a Toggle button it automatically changes the Switch's Boolean value 0 to 1. In other words the state is changed from off to on, and when we Tap on the switch it show it's state on the label.
To understand it we use the following.
Step 1
Open XCode by double-clicking on it.
Step 2
Create a New XCode Project by clicking on it.
Step 3
Now Select Single View Application and click on Next.
Step 4
Now provide your Product Name.
Step 5
Select the location where you want to save your project and click on Create.
Step 6
Now we write the code.
ViewController.h
//
// ViewController.h
// Switch
//
// Created by Sachin Bhardwaj on 10/12/12.
// Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
UILabel *switchLabel;
UISwitch *toggleSwitch;
}
@property (nonatomic,retain) IBOutlet UILabel *switchLabel;
@property (nonatomic,retain) IBOutlet UISwitch *toggleSwitch;
-(IBAction) switchValueChanged;
-(IBAction) toggleButtonPressed;
@end
ViewController.m
//
// ViewController.m
// Switch
//
// Created by Sachin Bhardwaj on 10/12/12.
// Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize switchLabel;
@synthesize toggleSwitch;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(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
Step 7
Finally we click on the Run button to show the output.
Step 8
Output 1 in iPhone:
Output 2 in iPhone:
Output 3 in iPhone:
Output 4 in iPhone: