1、基本用法:
CGFloat width = [[UIScreen mainScreen] bounds].size.width;
CGRect sliderFrame = CGRectMake(20, 100, width - 40, 50);//这里无论高度设为多少,都按其自己的默认高度显示
UISlider * slider = [[UISlider alloc] initWithFrame:sliderFrame];
slider.minimumValue = 0;//设置最小值
slider.maximumValue = 1;//设置最大值
slider.value = 0.3;//设置默认值
[self.view addSubview:slider];
效果:
2、注册响应事件:
slider.continuous = YES;//默认YES 如果设置为NO,则每次滑块停止移动后才触发事件
[slider addTarget:self action:@selector(sliderChange:) forControlEvents:UIControlEventValueChanged];
- (void) sliderChange:(id) sender {
if ([sender isKindOfClass:[UISlider class]]) {
UISlider * slider = sender;
CGFloat value = slider.value;
NSLog(@"%f", value);
self.view.backgroundColor = [UIColor colorWithRed:value green:value blue:value alpha:value];
}
}
3、给滑块,最小值一边,最大值一边配置颜色
slider.minimumTrackTintColor = [UIColor redColor];
slider.maximumTrackTintColor = [UIColor yellowColor];
slider.thumbTintColor = [UIColor purpleColor];
效果:
4、给滑块最大值、最小值一边设置图片:
UIImage * image1 = [UIImage imageNamed:@"apple.jpg"];
UIImage * image2 = [UIImage imageNamed:@"dog.png"];
slider.minimumValueImage = image1;
slider.maximumValueImage = image2;
看图最容易理解:
5、手动设置滑块的值,并是否动画移动过去:
- (void)setValue:(float)value animated:(BOOL)animated; // move slider at fixed velocity (i.e. duration depends on distance). does not send action
注:关于滑道和滑块的图片如果自己找不到,就别找了,自己做几个,在线PS很容易,做测试用的图片却是足够了,不会就自己百度一下吧,学一点儿是一点儿
下面的滑块以及滑道就是我自己做的,很粗糙,不过测试用嘛
- (void)setThumbImage:(nullable UIImage *)image forState:(UIControlState)state; //给滑动按钮设置图片
- (void)setMinimumTrackImage:(nullable UIImage *)image forState:(UIControlState)state;//给滑道左侧设置图片
- (void)setMaximumTrackImage:(nullable UIImage *)image forState:(UIControlState)state;//给滑道右侧设置图片
测试代码:
UIImage * image3 = [UIImage imageNamed:@"leftSlider.jpg"];
UIImage * image4 = [UIImage imageNamed:@"rightSlider.jpg"];
UIImage * image5 = [UIImage imageNamed:@"thumb1.jpg"];
UIImage * image6 = [UIImage imageNamed:@"thumb2.jpg"];
[slider setThumbImage:image5 forState:UIControlStateNormal];
[slider setThumbImage:image6 forState:UIControlStateHighlighted];
[slider setMinimumTrackImage:image3 forState:UIControlStateNormal];
[slider setMaximumTrackImage:image4 forState:UIControlStateNormal];
初始状态:
点击状态:
@property(nullable,nonatomic,readonly) UIImage *currentThumbImage;
@property(nullable,nonatomic,readonly) UIImage *currentMinimumTrackImage;
@property(nullable,nonatomic,readonly) UIImage *currentMaximumTrackImage;
8、定制UISlider
可以自定义一个类继承自UISlider,然后重写这些方法,返回自定义的滑块的各个区域的大小
- (CGRect)minimumValueImageRectForBounds:(CGRect)bounds; //返回左边图片大小
- (CGRect)maximumValueImageRectForBounds:(CGRect)bounds; //返回右边图片大小
- (CGRect)trackRectForBounds:(CGRect)bounds; //返回滑道大小
- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value; //返回滑块大小