iOS

Better Code: UISlider Basics for Apple iOS

Scott Kantner teaches the basics of slider operations and how to build a custom slider for your next app.

Sliders are great way to let your users easily set numeric values in your apps. For example, in the metronome app shown below, I've used a slider to let the user quickly set the tempo. Notice also that the slider has a custom appearance, which was accomplished by using custom images for the slider thumb and the track. In this post we'll learn the basics of slider operations and also how to create a custom slider similar to the one shown below. For this project, you'll need to download the three custom image files we've provided.

Start new project

Open Xcode and from the File menu, select New, and then New Project. A new workspace window will appear, and you will be presented with several application templates to choose from.

On the left-hand side, select Application from the iOS section. Select Single View Application and click the Next button.

Figure A

On the next pane, enter CustomSlider for the Product Name and com.myappcompany as the Company Identifier. (Feel free to substitute your own product name and company identifier).

Leave the Class Prefix as is. It should be blank - XYZ is just a placeholder hint.

Make sure only Use Automatic Reference Counting and Use Storyboards are checked.

Set Device Family to iPhone, and click Next.

Figure B

A new pane will appear asking you where you would like to save the project. XCode will create a CustomSlider project folder inside the directory you select.

Once the project is created, Xcode will open a workspace window with your new project.

Preparing to receive slider events

As the user moves the slider back and forth, it will send events to let us know the value is changing. We must provide a method for the slider to call, so in the Files and Groups pane, click on ViewController.m and add the following method directly under ViewDidLoad:

- (IBAction)sliderChanged:(id)sender
{
UISlider *slider = (UISlider *)sender;
float val = slider.value;
self.myLabel.text = [NSString stringWithFormat:@"%f",val];
}

IBAction is a macro that makes our method available to Interface Builder, which we'll need when setting up the user interface. When the slider calls our method, it passes a reference to itself as sender, but it is simply a generic object reference. Before we can reference the slider's properties, we must therefore cast it as a UISlider object. The slider always returns a floating point value, and the rest of our method simply changes the text of label to display that value.

Setting up the User Interface

Now click on MainStoryboard.storyboard. After it opens in Interface Builder, select the View object, click on the Attributes Inspector and then change the view's background color to a color of your choosing.

Next go to the Object Library located on the lower right-hand side of the workspace and drag a Label onto the view and center it just above the middle of the view. Then drag a Slider onto the view and center it just below the Label. For now, do not alter the size of the slider. Figure C shows the situation so far.

Figure C

Next, click on the Assistant Editor in the upper right corner of the Xcode Interface.

Figure D

The Assistant Editor will display ViewController.h in an adjacent pane as shown in Figure E. Click on the label to select it, then press the Control key and drag from the label to just under the word "@interface" in ViewController.h. When you release your finger from the mouse, the Connection dialog will appear. Type "myLabel" into the Name field and press Enter. You have now created an outlet named myLabel and connected it to the UILabel in the xib file. For more information on outlets, see Getting started with iOS Views and View Controllers: Part 1. Do the same for the slider using the name "mySlider".

Figure E

The final thing we need to do is connect the slider with our sliderChanged: method. Control drag from the slider over to View Controller as shown in Figure F. When you release the mouse, a popup will appear. Select sliderChanged: to make the connection, and then click on the Standard Editor button to remove the Assistant Editor window from the screen.

Figure F

Now build and run the app. Notice how the value changes from 0 to 1 as you move the slider. Go back to the storyboard and stretch the slider so it is nearly the width of the screen and run the app again. Note how the value now changes much more gradually because the slider has a wider range of motion.

Often it's most useful to have the slider return integer values within a specified range. To do that, go to ViewController.m and change viewDidLoad: as shown below:

- (void)viewDidLoad
{
[super viewDidLoad];
self.mySlider.minimumValue = 30;
self.mySlider.maximumValue = 240;
}
Then make the following changes to sliderChanged:
- (IBAction)sliderChanged:(id)sender
{
UISlider *slider = (UISlider *)sender;
NSInteger val = lround(slider.value);
self.myLabel.text = [NSString stringWithFormat:@"%d",val];
}

When we build and rerun the app this time, the slider returns integer values in our specified range from 30 to 240. Notice that the lround function converts the floating point value to an integer.

Dressing up the slider

A slider's appearance can be altered in a number of ways by modifying its properties. In our case, we're going to change both the thumb image that the user touches and the track that it runs on. There are three properties in play, as shown in Figure G.

Figure G

Drag the three image files you downloaded into your project right underneath ViewController.m. Make sure that "Copy items into destination group's folder" is checked before clicking Finish.

Figure H

Then add the following lines to viewDidLoad:

- (void)viewDidLoad
{
[super viewDidLoad];
self.mySlider.minimumValue = 30;
self.mySlider.maximumValue = 240;
[self.mySlider setThumbImage:[UIImage imageNamed:@"slider_tab.png"]
forState:UIControlStateNormal];
[self.mySlider setThumbImage:[UIImage imageNamed:@"slider_tab.png"]
forState:UIControlStateHighlighted];
[self.mySlider setMinimumTrackImage:[UIImage imageNamed:@"slider_minimum.png"]
forState:UIControlStateNormal];
[self.mySlider setMaximumTrackImage:[UIImage imageNamed:@"slider_maximum.png"]
forState:UIControlStateNormal];
}

The thumb image changes to a highlighted state when touched, so we must specify our custom image for both the touched (highlighted) and untouched (normal) states of the slider.

Build and run the app one more time and voila! We now have a much nice looking slider as shown below.

We've just scratched the surface of what's possible with UISlider, but you should now have the basics well in hand. As always, be sure to read Apple's excellent documentation to gain a deeper understanding. And if you'd like to know about the metronome app shown above, please feel free to contact me using the contact info below.

Also read:

About

Scott Kantner started his IT career on a Radio Shack TRS-80 model I back in 1978. He is CTO of a hosting/colocation firm, a tech writer, and an avid iOS app developer. He has several music-related apps in the App Store that you can learn about at OnS...

0 comments