3. Sliders
Sliders are used to modify a value over a finite range. A slider is made up of two parts: a thumb and a
track. The thumb is draggable across the width of
the slider. The track defines the width of the slider and gives a
proportional context for the position of the thumb. The standard slider
class included in UIKit is
UISlider.
You can create a slider by adding an instance as a subview to your
window or base UIView. As with other
UIControl classes, you should use the target-action
mechanism to set at least one target for events generated by the slider.
Your slider can send action messages to associated targets either as its
value changes or upon release of the slider. The UIControlEvent type for a changed value
in a slider is UIControlEventValueChanged. It’s
possible for a user to change values rapidly and often, so developers
should keep expensive operations to a minimum:
// Code for setting up a UISlider
#import "SliderViewController.h"
@implementation SliderViewController
- (void)viewDidLoad
{
standardSlider = [[UISlider alloc] initWithFrame:CGRectMake(60,20,200,40)];
[self.view addSubview:standardSlider];
[standardSlider addTarget:self action:@selector(sliderChanged:)
forControlEvents:UIControlEventValueChanged];
[super viewDidLoad];
}
- (void)sliderChanged:(id)sender
{
UISlider *slider = (UISlider *)sender;
NSLog(@"Slider changed. New value: %f.", slider.value);
}
- (void)dealloc
{
[standardSlider release];
[super dealloc];
}
@end
Figure 4 shows a standard
UISlider.
You can customize the look of a UISlider by
changing the images representing the thumb and by manipulating the color
of the track bar:
// Code for overriding the thumb image and track
#import "SliderViewController.h"
@implementation SliderViewController
- (void)viewDidLoad
{
standardSlider = [[UISlider alloc] initWithFrame:CGRectMake(60,20,200,40)];
[self.view addSubview:standardSlider];
customSlider = [[UISlider alloc] initWithFrame:CGRectMake(60,60,200,40)];
customSlider.backgroundColor = [UIColor clearColor];
[customSlider setThumbImage:[UIImage imageNamed:@"thumbOff.png"]
forState:UIControlStateNormal];
[customSlider setThumbImage:[UIImage imageNamed:@"thumbOn.png"]
forState:UIControlStateHighlighted];
UIImage *leftTrack = [[UIImage imageNamed:@"leftTrack.png"]
stretchableImageWithLeftCapWidth:5.0 topCapHeight:0.0];
UIImage *rightTrack = [[UIImage imageNamed:@"rightTrack.png"]
stretchableImageWithLeftCapWidth:5.0 topCapHeight:0.0];
[customSlider setMinimumTrackImage:leftTrack forState:UIControlStateNormal];
[customSlider setMaximumTrackImage:rightTrack forState:UIControlStateNormal];
[self.view addSubview:customSlider];
[super viewDidLoad];
}
- (void)dealloc
{
[standardSlider release];
[customSlider release];
[super dealloc];
}
@end
Figure 5 shows a
UISlider subclass with a custom thumb image.