-
Notifications
You must be signed in to change notification settings - Fork 1
A 1.6. Implementing Range Pickers with UISlider
To create a slider, instantiate an object of type UISlider. Let’s dive right in and create a slider and place it on our view controller’s view. We’ll start with our view controller’s implementation file:
#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UISlider *slider; @end
And now let’s go to the viewDidLoad method and create our slider component. In this code, we are going to give our slider a range between 0 and 100 and set its default position to be halfway between start and end.
- (void)viewDidLoad { [super viewDidLoad]; self.slider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, 200, 23)]; self.slider.center = self.view.center; self.slider.minimumValue = 0; self.slider.maximumValue = 100; self.slider.value = 50; [self.view addSubview:self.slider]; }
If you wish to receive an event whenever the slider’s thumb has moved, you must add your object as the target of the slider, using the slider’s addTarget:action:forControlEvents: method:
- (void) sliderValueChanged:(UISlider *)paramSender{ if ([paramSender isEqual:self.slider]) { //NSLog(@"New value = %f", paramSender.value); __unused float a = round(paramSender.value); self.label.text = [NSString stringWithFormat: @"%f", paramSender.value]; }
and add action:
[self.slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
I have prepared two images: one for the normal state of the thumb and the other one for the highlighted (touched) state of the thumb. Let’s go ahead and add them to the slider:
[self.slider setThumbImage:[UIImage imageNamed:@"ThumbNormal.png"] forState:UIControlStateNormal]; [self.slider setThumbImage:[UIImage imageNamed:@"ThumbHighlighted.png"] forState:UIControlStateHighlighted];
The following sample code instantiates a UISlider and places it at the center of the view of the view controller. It also sets the tint color of the minimum value tracking view of the slider to red, the tint color of the thumb view of the slider to black, and the tint color of the maximum value tracking view of the slider to green:
self.slider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, 200, 23)]; self.slider.center = self.view.center; self.slider.minimumValue = 0; self.slider.maximumValue = 100; self.slider.value = 50; [self.view addSubview:self.slider]; /* Set the tint color of the minimum value */ self.slider.minimumTrackTintColor = [UIColor redColor]; /* Set the tint color of the thumb */ self.slider.maximumTrackTintColor = [UIColor greenColor]; /* Set the tint color of the maximum value */ self.slider.thumbTintColor = [UIColor blackColor];