How To Toggle Switch In iPhone

This is the very simple example. In this example we will see how we can change the background color
after toggling switch in the application. So let see how it will worked. My previous post you can find out
from here (Please attached the link).

Step 1: Create a View-base application using the template . Name the project “ColorChange”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: Expand classes and notice Interface Builder created the ColorChangeViewController class for you. Expand Resources and notice the template generated a separate nib, ColorChangeViewController.xib for the SimpleExampleViewController.

Step 4: Open the ColorChangeViewController.h file and make the following changes in the file.


#import <uikit/UIKit.h>
@interface ColorChangeViewController : UIViewController {
UIView *redView;
UIView *yellowView ;
@property (nonatomic, retain) IBOutlet UISwitch *Switch1;
@property (nonatomic, retain) UIView *redView;
@property (nonatomic, retain) UIView *yellowView;
- (IBAction)ChangeColor:(id)sender;



Step 5: Double click the ColorChangeViewController.xib file and open it to the Interface Builder. First
drag the switch from the library and place it to the View Window. Connect File’s owner icon to the
switch and select Switch1, and select switch and bring up connection Inspector, connect Touch Up Inside
to the File’s Owner icon and select ChangeColor: method. Now save the .xib file, close it and go back to
the Xcode.

Step 6: In the ColorChangeViewController.m file make the following changes:


#import "ColorChangeViewController.h"
@implementation ColorChangeViewController
@synthesize Switch1,redView,yellowView;
- (void)viewDidLoad
[super viewDidLoad];
- (void)viewDidUnload
[super viewDidUnload];
- (IBAction)ChangeColor:(id)sender
UISwitch *swt = (UISwitch *)sender;
if (swt.on)
CGRect redFrame = CGRectMake(20, 140, 280, 300);
redView = [[UIView alloc] initWithFrame:redFrame];
redView.backgroundColor = [UIColor redColor];
[yellowView removeFromSuperview];
[self.view addSubview:redView];
[redView release];
CGRect yellowFrame = CGRectMake(20, 140, 280, 300);
yellowView = [[UIView alloc] initWithFrame:yellowFrame];
yellowView.backgroundColor = [UIColor yellowColor];
[redView removeFromSuperview];
[self.view addSubview:yellowView];
[yellowView release];
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);



Step 7: Now Compile and run the application on the Simulator.

You can Download SourceCode from here Toggle Switch Source Code.

Leave a Comment:

1 comment
Nat says November 24, 2012

Added this to viewDidLoad to set colour on run:

UISwitch *sw = [[UISwitch alloc]init];
sw.on = TRUE;
[self ChangeColor:sw];

Add Your Reply