The UISlider control’s value is a floating point number between its minimum and maximum values, inclusive. So how can we use the value of a slider to index into an array? Read on to find out!
Start Xcode, choose “Create a new Xcode project” and select the Single View Application template. Name the application “SliderList,” and choose options as shown here:
Click Next, choose a location to save the project, and click Create.
In ViewController.xib, drag a slider and a label to the view as shown:
Change the text of the label to read “January”, and min and max values of the slider to 0 and 11. Make sure the current value of the slider is set to 0.
Open ViewController.h and make these changes:
@interface ViewController : UIViewController
@property (nonatomic, weak) IBOutlet UILabel *month;
– (IBAction)sliderValueChanged:(UISlider *)sender;
@end
The month outlet should be wired to the UILabel control and the sliderValueChanged method should be wired to the slider’s ValueChanged event in Interface Builder.
Now open ViewController.m and make these changes:
NSArray *monthArray;
@interface ViewController ()
@end
@implementation ViewController
@synthesize month;
– (IBAction)sliderValueChanged:(UISlider *)sender
{
self.month.text = [monthArray objectAtIndex:sender.value];
}
– (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
monthArray = [NSArray arrayWithObjects:
@"January", @"February", @"March",
@"April", @"May", @"June",
@"July", @"August", @"September",
@"October", @"November", @"December", nil];
}
– (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
– (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end
Note that we’ve made a private variable called monthArray at the top of the file. This NSArray doesn’t need to be seen by any class but this one, so this is the proper way to do this. We instantiate and initialize this array in viewDidLoad with the months of the year as NSStrings.
In sliderValueChanged: it is a simple matter of indexing into the monthArray using the slider’s value. But array indexes are int, and the sender’s value is float! How does this work?
The answer is C’s type conversion logic. If the value of an expression doesn’t match the value the receiver expects, the compiler will make an attempt to cast the expression result to the expected value of the receiver. Here, the floating point value of the slider is being implicitly typed to int!
Run the app, and change the value of the slider to see each month in the array:



