UISlider Tutorial

iOS comes with a built in user control that you can use to get input from your users. UISlider is the name of this user control. This is a great way to get a numerical value from 1 to 100. You see this used in apps that ask for ratings and also apps that want control over settings like volume.

This is pretty simple to implement – if you want to follow along be sure to have XCode 4 installed and create a new view based iOS project. You can pick iPhone, iPad or both and UISlider works the same in each of these. The easiest thing to do is to pick an iPhone project.

UISlider Example

Here is what the finished project looks like:

 

I set the slider to go from 1 to 100 but you can choose any range that you want.

Implement UISlider In Only 5 Steps With XCode 4

  • Add UISlider to your view in Interface Builder
  • Code UISlider IBOutlet in your view controller h and m files
  • Connect the UISlider in Interface Builder to your UISlider IBOutlet in your view controller
  • Code an IBAction that updates your UI when the slider moves (locate on your view controller h and m files)
  • Connect this IBAction to the UISlider in Interface Builder

 

UISlider Sample Code

Here is the code that I use in the video (don’t forget to set up the view in Interface Builder and make all the connections).

View Controller Header File (h)

#import <UIKit/UIKit.h>
@interface Slider_Sample_CodeViewController : UIViewController {
UILabel *label;
}
@property(nonatomic, retain) IBOutlet UILabel *label;
-(IBAction)updateLabel:(UISlider *)sender;
@end

 

View Controller Implementation File (m)

#import "Slider_Sample_CodeViewController.h"
@implementation Slider_Sample_CodeViewController
@synthesize label;
- (void)dealloc{
[label release];
[super dealloc];
}
-(IBAction)updateLabel:(UISlider *)sender{
self.label.text = [NSString stringWithFormat:@"Value: %f", sender.value];
}
@end

One thought on “UISlider Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>