Slider is a horizontal bar with a slider button which can slide along the bar’s length. The value of the slider changes according to the position of the slider button and this value can be displayed on a label beside the slider. This is precisely what we are going to do in this tutorial.

Slider can be used as a value setter for a particular object such as a volume control.

Step 1: Start Xcode and create a view based application with name “SliderDemo”.

Step 2: Open “SliderDemoViewController.h” and put the following code in it.

 @interface SliderDemoViewController : UIViewController {
			UILabel *sliderLabel;

}

@property (nonatomic,retain) IBOutlet UILabel *sliderLabel;

-(IBAction) sliderChanged:(id) sender;

@end

Put the following code in the “SliderDemoViewController.m” file.

@implementation SliderDemoViewController
@synthesize sliderLabel;

- (void)dealloc {
	[sliderLabel release];
    	[super dealloc];
}

-(IBAction) sliderChanged:(id) sender{
	UISlider *slider = (UISlider *) sender;
	int progressAsInt =(int)(slider.value + 0.5f);
	NSString *newText =[[NSString alloc]
                  initWithFormat:@"%d",progressAsInt];
  self.sliderLabel.text = newText;
	[newText release];
}

@end

Here, in the sliderChanged method, we have declared an object of type slider. The variable progressAsInt has been used to store the slider’s position.0.5f is added to the slider value to round it off. We then put the value of progressAsInt in a string and set it as the label’s text.

Step 3: Save(command+s) the project. Now open the “SliderDemoViewController.xib” file from the Resources folder. Add a slider and a label beside it to the view as shown below.
SliderDemoViewController.xib

Open the Attributes Inspector for slider.Set the fields under Values as Minimum = 1,Maximum = 100 and Initial = 50.

Step 4: Open the Connections Inspector(command+2) for slider. Connect the value changed link to the sliderChanged method in File’s Owner. Also connect the label to sliderLabel in the File’s Owner.

Step 5: Save,build and run the project. Now as you slide the slider button, the value displayed by the label changes.

You can download the source code here.

OUTPUT:
Output for SliderDemo

Thats the end of the tutorial folks. You are now ready to dabble with your own version of slider.