- 做項(xiàng)目的時(shí)候碰到的一個(gè)需求:需要Slider可以點(diǎn)擊滑動(dòng)并且Slider的滑塊需要移動(dòng)到固定的四個(gè)位置埋嵌;
- 其效果可以參考網(wǎng)易新聞客戶端的調(diào)整字體第步。
一均驶、實(shí)現(xiàn)步驟
1.初始化UISlider
- (UISlider *) fontSlider {
if (!_fontSlider) {
_fontSlider = [[UISlider alloc] initWithFrame:CGRectMake(15,64, CGRectGetWidth(self.bounds) - 15 * 2, 44)];
_fontSlider.minimumValue = 0;
_fontSlider.maximumValue = 3;
_fontSlider.backgroundColor = [UIColor clearColor];
[_fontSlider setThumbImage:[UIImage imageNamed:"thumb.png"] forState:UIControlStateNormal];
_fontSlider.minimumTrackTintColor = [UIColor clearColor];
_fontSlider.maximumTrackTintColor = [UIColor clearColor];
[_fontSlider setValue:0 animated:YES];
//添加滑動(dòng)事件
[_fontSlider addTarget:self
action:@selector(fontSliderValueChanged:)
forControlEvents:UIControlEventValueChanged];
//添加點(diǎn)擊手勢(shì)
[_fontSlider addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fontSliderTapped:)]];
}
return _fontSlider;
}
2.事件和手勢(shì)
- (void) fontSliderValueChanged:(id)sender {
UISlider *slider = sender;
//將slider的value+0.5然后取整(向下取整)曹质,那么index只能是0有梆,1赁炎,2和3這四個(gè)數(shù)字了醉箕,所以slider只能在這四個(gè)位置上跳動(dòng)
NSUInteger index = (NSUInteger)(slider.value + 0.5);
[self.fontSlider setValue:sliderValue animated:YES];
}
- (void) fontSliderTapped:(UITapGestureRecognizer *)tapGesture {
CGPoint touchPoint = [tapGesture locationInView:self.fontSlider];
CGFloat value = (self.fontSlider.maximumValue - self.fontSlider.minimumValue) * (touchPoint.x / self.fontSlider.frame.size.width );
NSUInteger index = (NSUInteger)(value + 0.5);
[self.fontSlider setValue:sliderValue animated:YES];
}