How to Use a Slider

Matthew Campbell, June 4th

You are probably familiar with the slider control – a sliderlooks something like this:

To demonstrate this control we are going to build on the view controller post I wrote last week. If you haven’t yet read that click on this article to do so:

How to Use a View Controller Programatically

Or simply assume that you are working from within a subclass of UIViewController for this example. Last week we already added a UILabel control – we will keep this and use that to demonstrate the behavior of the slider.

Let’s add a UISlider control by putting in the required code under the @implementation statement in our ViewController implementation file.

Make sure to release this slider in the dealloc method:


Now, we need to instantiate the slider object in the loadView method just like we did for the label last week.

As you can see above we also set some initial properties here: min and max value and the starting value.


Now, we need to add an action so when the user touches the slider something will happen. We use what is called target-action to do this. Essentially, we are assigning a method to execute (the action) when an event occurs. We also need to tell the system where the action is coded (the target).

In our example, we are going to assign an action, updateLabel, to execute when the UIControlEventValueChanged event occurs. The target will be the view controller so we can simply use the self keyword to assign this action.

Here is the line of the code we will use to do this:

Finally, we need to add the slider to the view controller’s view:

The Entire loadView Method

Here is what the entire loadView method looks like, including the label code we added last week:

Add the Action Method

Remember that above we assigned an action to the slider object. We still need to add this code otherwise when the user touches the slide control our app will crash instead of doing something useful.

This code will update the label with the value that corresponds to where the user slides the control.

Now, when you add this code and run your app you should see a slider that you can use to pick a number between 1 and 100. When the simulator first launches you will see a 10 displayed since we set the starting value way back in the loadView method.

Next week I will attempt to demonstrate this same example using Interface Builder. Stay tuned!

How to Use a Slider…

You’ve been kicked (a good thing) – Trackback from – iPhone SDK links, community driven…

[...] WinePad How to Use a Slider June 4, 2009, 1:42 pm Filed under: Uncategorized (My Original Blog Post: [...]

  • Hours of videos, demos & screen casts
  • Detailed HANDS-ON Exercises
  • Much Much Much More
  • UIKit
  • Objective-C
  • Core Data
  • More!
  • Learn How To Make An iPhone App right now using my proven system.

    PS: Tons of us are having a blast living off our own code, join us now. Click here to get all the details.