Top of the page
Close

This is a red error

This is a red error

This is a red error

UISwitch tutorial - example how to use the Switch in XCode for iPhone, sample included

Ondrej Rafaj on 2009.08.12 14:59:18

Attached files
30-UISwitch.zip Download
UISlider tutorial.docx Download

Today I'll show you how to use UISwitch component in iPhone SDK. We will have three instances of UISwitch controlling three different components, UILabel, another UISwitch and UITextField, it is quite simple. Enjoy yourself :)

First of all, start a new project. Let's say View-Based Application and to make everything easier to explain, call it "TutorialProject".

Open the TutorialProjectViewController.xib file. In Interface Builder place View into the new window (Library » Cocoa Touch » Windows, Views & Bars) and place four instances of the UISwitch onto the View and one UITextField and one UILabel. Check out some of those pictures below to see where to place them.

Open the TutorialProjectViewController.h paste those parts enclosed by // ------ Tutorial code starts / ends here ------:

//
//  TutorialProjectViewController.h
//  TutorialProject
//
//  Created by Ondrej Rafaj on 5.8.09.
//  Copyright Home 2009. All rights reserved.
//

#import 

@interface TutorialProjectViewController : UIViewController {
	
	// ------ Tutorial code starts here ------
	
	IBOutlet UISwitch *switch1;
	IBOutlet UISwitch *switch2;
	IBOutlet UISwitch *switch3;
	
	IBOutlet UILabel *resLabel;
	IBOutlet UISwitch *resSwitch;
	IBOutlet UITextField *resTextField;
	
	// ------ Tutorial code ends here ------
	
	
}

// ------ Tutorial code starts here ------

@property (nonatomic, retain) UISwitch *switch1;
@property (nonatomic, retain) UISwitch *switch2;
@property (nonatomic, retain) UISwitch *switch3;

@property (nonatomic, retain) UILabel *resLabel;
@property (nonatomic, retain) UISwitch *resSwitch;
@property (nonatomic, retain) UITextField *resTextField;

- (IBAction) toggleEnabledForSwitch1: (id) sender;
- (IBAction) toggleEnabledForSwitch2: (id) sender;
- (IBAction) toggleEnabledForSwitch3: (id) sender;

// ------ Tutorial code ends here ------

// This function is for button which takes you to the xprogress.com website
- (IBAction) runXprogressComButton: (id) sender;

@end

In the first part:

IBOutlet UISwitch *switch1;
IBOutlet UISwitch *switch2;
IBOutlet UISwitch *switch3;
	
IBOutlet UILabel *resLabel;
IBOutlet UISwitch *resSwitch;
IBOutlet UITextField *resTextField;

We are declaring variables for all the elements on the View, these, once assigned to te element in Interface Builder are responsible for all the actions you may want to do with them. There are three switches (left side of the application) and three elements starting on res

In the second part:

@property (nonatomic, retain) UISwitch *switch1;
@property (nonatomic, retain) UISwitch *switch2;
@property (nonatomic, retain) UISwitch *switch3;

@property (nonatomic, retain) UILabel *resLabel;
@property (nonatomic, retain) UISwitch *resSwitch;
@property (nonatomic, retain) UITextField *resTextField;

- (IBAction) toggleEnabledTextForSwitch1onSomeLabel: (id) sender;
- (IBAction) toggleEnabledTextFieldForSwitch2: (id) sender;
- (IBAction) toggleOnForSwitch3: (id) sender;

We are setting up the properties (@property) and functions which are going to handle the action when the status of the your switch will change (starting on IBAction)

Next file we need to edit is the TutorialProjectViewController.m the code will look like that:

//
//  TutorialProjectViewController.m
//  TutorialProject
//
//  Created by Ondrej Rafaj on 5.8.09.
//  Copyright Home 2009. All rights reserved.
//

#import "TutorialProjectViewController.h"

@implementation TutorialProjectViewController

// ------ Tutorial code starts here ------

@synthesize switch1;
@synthesize switch2;
@synthesize switch3;

@synthesize resLabel;
@synthesize resSwitch;
@synthesize resTextField;

- (IBAction) toggleEnabledTextForSwitch1onSomeLabel: (id) sender {
	if (switch1.on) resLabel.text = @"Enabled";
	else resLabel.text = @"Disabled";
}

- (IBAction) toggleEnabledTextFieldForSwitch2: (id) sender {
	if (switch2.on) resTextField.enabled = YES;
	else {
		resTextField.enabled = NO;
		resTextField.text = @"Disabled";
	}
}

- (IBAction) toggleOnForSwitch3: (id) sender {
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration: 0.2];
	
	if (switch3.on) resSwitch.on = YES;
	else resSwitch.on = NO;
	
	[UIView commitAnimations];
}


// ------ Tutorial code ends here ------


/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

// This function is for button which takes you to the xprogress.com website
- (IBAction) runXprogressComButton: (id) sender {
	NSURL *url = [ [ NSURL alloc ] initWithString: @"http://www.xprogress.com/" ];
	[[UIApplication sharedApplication] openURL:url];
}


- (void)dealloc {
    
	// ------ Tutorial code starts here ------
	
	[switch1 release];
	[switch2 release];
	[switch3 release];
	
	[resLabel release];
	[resSwitch release];
	[resTextField release];
	
	// ------ Tutorial code ends here ------
	
	[super dealloc];
}

@end

In the first part of the code we need to synthesize all the variables (This will automatically create all the functionality you'll need, like set or get the data from the variable)

@synthesize switch1;
@synthesize switch2;
@synthesize switch3;

@synthesize resLabel;
@synthesize resSwitch;
@synthesize resTextField;

Than we need to create all the actual functions which are going to handle action after the stats of the UISwitch will change:

- (IBAction) toggleEnabledTextForSwitch1onSomeLabel: (id) sender {
	if (switch1.on) resLabel.text = @"Enabled";
	else resLabel.text = @"Disabled";
}

- (IBAction) toggleEnabledTextFieldForSwitch2: (id) sender {
	if (switch2.on) resTextField.enabled = YES;
	else {
		resTextField.enabled = NO;
		resTextField.text = @"Disabled field";
	}
}

- (IBAction) toggleOnForSwitch3: (id) sender {
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration: 0.3];
	
	if (switch3.on) resSwitch.on = YES;
	else resSwitch.on = NO;
	
	[UIView commitAnimations];
}

First function, toggleEnabledTextForSwitch1onSomeLabel, is setting text of your label to Enabled if the switch one is ON and disabled if the switch is OFF

Second function, toggleEnabledTextFieldForSwitch2, is actually enabling and disabling the text field and additionally, once the field is disabled, is setting the text property of the field to "Disabled field"

Third function toggleOnForSwitch3 is the most complicated one. This function is setting the other switch to the same position as is the first one. All the code which is closed into square brackets is handling how smoothly is the responding switch changing it's state. You can try to disable this functionality or change the delay for the animation like that:

- (IBAction) toggleOnForSwitch3: (id) sender {
	//[UIView beginAnimations:nil context:NULL];
	//[UIView setAnimationDuration: 0.2];

	// this will just switch the second switch without any animation
	if (switch3.on) resSwitch.on = YES;
	else resSwitch.on = NO;
	
	//[UIView commitAnimations];
}

or

- (IBAction) toggleOnForSwitch3: (id) sender {
	[UIView beginAnimations:nil context:NULL];

	// Now I am extending the animation time
	[UIView setAnimationDuration: 0.8];

	if (switch3.on) resSwitch.on = YES;
	else resSwitch.on = NO;
	
	[UIView commitAnimations];
}

The coding part is now done and we can start connecting the code to the interface in Interface Builder

Open the TutorialProjectViewController.xib file and than the first thing we need to is to connect all the elements to their variables. Press Ctrl key and hold it, drag the "File's owner icon from the list. This will create nice blue line connecting File's owner and your pointed, than release the mouse over the switch one (drag and drop while holding Ctrl) and you'll see menu with all the variables with UISwitch type we've declared. In this case select switch1

Connecting switch1

Once the switch1 is connected with it's component, connect switch2 and switch3

Connecting switch2

Connecting switch3

Now when you have these connected, I can tell you that we are not using these variables to control anything, but I was expecting you messing around the app, once we will be done and those connections may become quite handy

Now please dothe same connections with "res" variables (resLabel, resTextField, resSwitch) following these pictures:

Connecting resLabel

Connecting resTextField

Connecting resSwitch

Now we need to connect our switches to the functions we've created. Now we have two options how to do that, first one is to hold the Ctrl key again and than drag the switch you want to assign the function to and drop it over the "File's owner" icon and than select the function you want to use from the small pop-up menu OR as you can see on those following pictures right click on the switch and drag the small circle on the right side of the line with "Value changed" and than drop it over the "File's owner" icon and the rest is the same, you just need to pick the correct function.

Here you can see how the connecting works.

Connecting uiswitch to the function

Select the toggleEnabledTextForSwitch1onSomeLabel function for "Label switch"

Connecting uiswitch to the function

Select the toggleEnabledTextFieldForSwitch2 function for "TextField switch"

Connecting uiswitch to the function

Select the toggleOnForSwitch3 function for "Switch switch" :)

Connecting uiswitch to the function

Only remaining thing we need to do is cross fingers and launch the application :)

It should look like that:

Connecting uiswitch to the function

I hope that you've enjoyed this tutorial and that I helped you a little bit on your "Path of the iPhone developer". And I hope tat you will come back soon to check other new tutorials .... I you found any grammatical mistake I've made please tell me, I am not a native speaker than I will really appreciate any comment from your side.

See u soon,
Ondrej

Ondrej Rafaj

Ondrej Rafaj

Technical director @ Fuerte International

Back to top Comment

Comments ... Why not to get involved!
HTML Comment Box is loading comments...

Old comments:

  • Olivia

    Olivia

    from 72.199.**.** @   

    Ondrej, Nice tutorial!! Thanks for making this!!

  • andy

    andy

    from 67.9.**.** @   

    this was a very useful tutorial. thanks!

Back to top

IE SUCKS, DON'T USE IT :) Digg this page