Programming Sliders

After you slide the Slider control and label onto the page, how do you get them to work together? Here is the code I use to make a UISlider change the text of a UILabel. (Xcode 3)
.h file:

@interface SampleViewController : UIViewController
IBOutlet UISlider *controlTwo;
IBOutlet UILabel *labelTwo;

I use a common word at the end of each element when they are related; in this case, “Two.”

@property (nonatomic, retain) UISlider *controlTwo;
@property (nonatomic, retain) UILabel *labelTwo;
– (IBAction)sliderActionToLabelTwo:(id)sender;


After typing in the above, open Interface Builder and drag from File’s Owner to the slider and select “controlTwo.” Drag from File’s Owner to the label and select “labelTwo.”  The control will be acting on the label, so right-click on the control, click on the circle for Value Changed, and left-drag it to File’s Owner and select the IB Action “sliderActionToLabelTwo.” Save in IB and return to Xcode.
.m file:

#import “SampleViewController.h”
@implementation SampleViewController

@synthesize controlTwo;
@synthesize labelTwo;

#pragma mark –
#pragma mark controlTwo Action

If your segmented control uses images in the buttons, or if you need to localize each option, use the following.

#pragma mark –
#pragma mark controlTwo Action

– (IBAction)sliderActionToLabelTwo:(id)sender{

NSArray *arrayTwo = [NSArray arrayWithObjects: @”-1.0″, @”-0.5″, @”0.0″, @”0.5″, @”1.0″, @”1.5″, @”2.0″, @”2.5″, @”3.0″, nil];

NSString *labelValueTwo;
labelValueTwo = [arrayTwo objectAtIndex:(int)controlTwo.value];
labelTwo.text = [NSString stringWithFormat:@”%@”, labelValueTwo];
In IB, in the Tools>Attributes Inspector for the Slider, under Values, change the minimum and maximum values to match your array. In this case, count the number of values in the array, starting with 0. In arrayTwo, there are 9 values. So for Minimum put “0.0” and for Maximum put “8.0” in the box.

For the initial value, count from the beginning of arrayTwo, starting with 0, and note the count for the value for where you want to the slider to begin. If you want the opening value to be variable -0.5, you’ll put “1” in the box. Check the box marked Continuous if you want the label to be continually updated as the slider is moved.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s