iOS 自定义slider点击移动和跳变

  1. 做项目的时候碰到的一个需求:需要Slider可以点击滑动并且Slider的滑块需要移动到固定的四个位置;
  2. 其效果可以参考网易新闻客户端的调整字体。

一、实现步骤
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];
        //添加滑动事件
        [_fontSlider addTarget:self
                        action:@selector(fontSliderValueChanged:)
              forControlEvents:UIControlEventValueChanged];
        //添加点击手势
        [_fontSlider addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fontSliderTapped:)]];
    }
    return _fontSlider;
}

2.事件和手势

- (void) fontSliderValueChanged:(id)sender {
    UISlider *slider = sender;
    //将slider的value+0.5然后取整(向下取整),那么index只能是0,1,2和3这四个数字了,所以slider只能在这四个位置上跳动
    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];
}

你可能感兴趣的:(iOS 自定义slider点击移动和跳变)