Change values with UISlider

A UISlider object is a visual control used to select a single value from a continuous range of values. Sliders are always displayed as horizontal bars. An indicator, or thumb, notes the current value of the slider and can be moved by the user to change the setting. In this tutorial, we display an UISlider and a Label. When moving the slider, the corresponding value will be displayed in the Label.

Update: May 12, 2014. This tutorial is made with Xcode 4 and targeted for iOS 6. The fully updated version for iOS7 and Xcode 5 is available here.

Create a new Project, select The Single View Application template.

Use the following project options

Open the iOSViewController.xib file and drag an UISlider and a Label onto the View. Give the Label an initial value of 0.

Open the assistant editor and ctrl-drag from the UISlider to the  iOSViewController.h file between the @interface and @end section to create the following outlet

Next, ctrl- drag from the label to the  iOSViewController.h file between the @interface and @end section to create the following outlet

The following lines are created in iOSViewController.h

@property (weak, nonatomic) IBOutlet UISlider *mySlider; 
@property (weak, nonatomic) IBOutlet UILabel *myLabel;

ctrl-drag from the UISlider to the  iOSViewController.h file between the @interface and @end section to create the following Action. This action method will be called when the user moves the UISLider. The following line is created in iOSViewController.h

- (IBAction)sliderValueChanged:(UISlider *)sender;

In iOSViewController.m the sliderValueChanged stub method is created. Now change this method to

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

The value property of UISLider is of type double. With a cast we transform the double to an integer. Now, Build and Run. Move the slider and see how the value will be updated in the label

You can download the source code of UISLiderTutorial at the ioscreator repository on github.