Top of the page
Close

This is a red error

This is a red error

This is a red error

UISlider tutorial - example how to use slider in iPhone SDK / XCode

Ondrej Rafaj on 2009.09.16 14:48:33

Attached files
UISlider tutorial.docx Download
UISlider.zip Download

Hi, Today I want to show you how to use the UISlider. After finishing this tutorial you will be able to read a value from the slider and set a new value from text field (UITextField) after pressing the button (UIButton). All source codes and printable MS Word document are included.

Lets get started. First of all you need to create a new project, it will be View-Based Application called TutorialProject and I am assuming that you already know how to do that :).

Once your new project has been created open the TutorialProjectViewController.xib file in interface builder and place one UISlider, one UITextField and one UIButton on the stage.

The interface should look like that:

LAyout of the application

Now you can run your application but only thing you will get is just set of those elements without any functionality.

Next step is in the code. Open the TutorialProjectViewController.h file and within the TutorialProjectViewController interface create two IBOutlets, one for the text field and one for the slider.

@interface TutorialProjectViewController : UIViewController {
	
	// ------ Tutorial code starts here ------
	
	IBOutlet UISlider *mySlider;
	IBOutlet UITextField *myTextField;
	
	// ------ Tutorial code ends here ------
		
}

after that you need to create two properties for those elements:

@property (nonatomic, retain) IBOutlet UISlider *mySlider;
@property (nonatomic, retain) IBOutlet UITextField *myTextField;

and the last two things we need to declare are out IBAction methods which are responsible for handling events generated by the UISlider (when the value will change) and the UIButton (to set a new value for the slider).

- (IBAction) sliderValueChanged:(id)sender;
- (IBAction) changeButtonPressed:(id)sender;

The entire code will look like that:

//
//  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 UISlider *mySlider;
	IBOutlet UITextField *myTextField;
	
	// ------ Tutorial code ends here ------
	
}

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

@property (nonatomic, retain) IBOutlet UISlider *mySlider;
@property (nonatomic, retain) IBOutlet UITextField *myTextField;

- (IBAction) sliderValueChanged:(id)sender;
- (IBAction) changeButtonPressed:(id)sender;

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

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

@end 

Now when we have our header file ready, we need to write the actual code for our elements and actions. Open the TutorialProjectViewController.m file and synthesize our two outlets right after the @implementation

@synthesize mySlider, myTextField;

Now we are going to set the first event function which handles value change event from UISlider.

- (IBAction) sliderValueChanged:(UISlider *)sender {
	myTextField.text = [NSString stringWithFormat:@"%.1f", [sender value]];
}

Here we are passing the UISlider object as a parameter into the function. And inside of the function we are setting the text value for our UITextField. Because value of the slider is as a float (which is a decimal number (Ex 66.6 :) )) we need to convert it into the format suitable for the text field by setting NSString stringWithFormat with formatting for the decimal number which is %.1f.

Next function will handle setting of the new value to the UISlider object.

- (IBAction) changeButtonPressed:(id)sender {
	NSString *textValue = [myTextField text];
	float value = [textValue floatValue];
	if (value < 0) value = 0;
	if (value > 100) value = 100;
	mySlider.value = value;
	myTextField.text = [NSString stringWithFormat:@"%.1f", value];
	if ([myTextField canResignFirstResponder]) [myTextField resignFirstResponder];
}

First we need to put the text from the NSTextField to NSString variable, to be able to get the value as a number (float):

NSString *textValue = [myTextField text];

Now we need to get the number:

float value = [textValue floatValue];

Check if the value is within the limits of the slider and set the actual value to the slider and back to the text field. I am setting the value to the text field because if user will set number which is not within the limits for the slider, they will see this immediately after pressing the button:

if (value < 0) value = 0;
if (value > 100) value = 100;
mySlider.value = value;
myTextField.text = [NSString stringWithFormat:@"%.1f", value];

Last and very important row is saying that the first responder after we clicked on the text field (which is the keyboard), should resign (means hide) because we’ve pressed the change button and we don’t need the keyboard anymore.

if ([myTextField canResignFirstResponder]) [myTextField resignFirstResponder];

Last function will be called automatically every time, we will stop editing the text field and touch something else on the display. This functionality is not necessary to run the app, but do this always, otherwise it will be a bad experience for your users when they will be unable to make the keyboard disappear. :)

- (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
	if (myTextField) {
		if ([myTextField canResignFirstResponder]) [myTextField resignFirstResponder];
	}
	[super touchesBegan: touches withEvent: event];
}

Another thing we can’t forget is to release all the used objects from the memory. You can do that in the pre-generated dealloc (de allocate) function on the bottom of the file.

[mySlider release];
[myTextField release];

The entire file should 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 mySlider, myTextField;

- (IBAction) sliderValueChanged:(UISlider *)sender {
	myTextField.text = [NSString stringWithFormat:@" %.1f", [sender value]];
}

- (IBAction) changeButtonPressed:(id)sender {
	NSString *textValue = [myTextField text];
	float value = [textValue floatValue];
	if (value < 0) value = 0;
	if (value > 100) value = 100;
	mySlider.value = value;
	myTextField.text = [NSString stringWithFormat:@"%.1f", value];
	if ([myTextField canResignFirstResponder]) [myTextField resignFirstResponder];
}

- (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
	if (myTextField) {
		if ([myTextField canResignFirstResponder]) [myTextField resignFirstResponder];
	}
	[super touchesBegan: touches withEvent: event];
}

// ------ 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 ------
	
	[mySlider release];
	[myTextField release];
	
	// ------ Tutorial code ends here ------
	
	[super dealloc];
}

@end

Now when all the coding is done, we can do something (at least for me) more interesting, and that’s the work with Interface Builder. Open the TutorialProjectViewController.xib file again in the IB (Interface Builder) and first we will is to set the UISlider. Click on it and open the Slider Properties tab in the Properties window and set the maximum value to 100 and initial value to 0. It should look like that:

Changing values of the UISlider

Next thing will be double click on the UITextField and type just zero (0) to have some initial value for the field. Now we will start connecting all the elements we’ve created to their "in code" equivalents. Hold the Ctrl (Control) key and try to drag the File’s Owner icon and drop it over the text field.

Connecting UITextField

Select your "myTextField" variable we’ve created in the code.

Selecting variable for the UITextField

Than do the same thing for the slider:

Selecting variable for the UISlider

And select the "mySliderVariable".

Selecting variable for the UISlider

Now we need to attach button and slider events. Start by right-clicking on the UIButton and you’ll see menu like on the next picture. Scroll for the "Touch Up Inside" event, drag the little circle on the right and drop if over the File’s Owner icon.

Connecting UIButton event

and selecting the "changeButtonPressed" event function.

Connecting UIButton event

Now do the same thing for the UISlider.

Right-click and connect Value Changed from the menu with File’s Owner.

Connecting UISlider event

And select the "sliderValueChanged" function.

Connecting UISlider event

Wooohooo, we are finishing … :)))

Save the NIB (.xib) file and go back to the XCode editor and run the application.

Final example of UISlider in iPhone simulator

And that’s all folks,

I hope I’ll see you in my Google Analytics stats again. Happy coding.

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:

  • montalat

    montalat

    from 86.74.**.** @   

    how can i keep the slider value even if i turn off the application ?.
    i mean next time i open the app i want see the last value in the text field
    Thx

  • Ondrej

    Ondrej

    from 94.193.**.** @   

    Hi,

    you can use NSUserDefaults to hold the data for example:

    [[NSUserDefaults standardUserDefaults] setObject:yourValue forKey:@"mySliderValue"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    and when the application starts just call:
    int myValueForSlider = [[NSUserDefaults standardUserDefaults] objectForKey:@"mySliderValue"];

    just make sure that you are not returning this value when there's none :)

    Cheers,

    Ondrej

Back to top

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