How to enable “tap and slide” in a UISlider?

后端 未结 14 589
不知归路
不知归路 2020-12-03 20:54

What I want to get is a UISlider which lets the user not only slide when he starts on its thumbRect, but also when he taps elsewhere. When the user

14条回答
  •  情话喂你
    2020-12-03 21:38

    You should add a tap gesture on your UISlider.

    Exemple :

     UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTapped:)];
        [_slider addGestureRecognizer:tapGestureRecognizer];
    

    In sliderTapped you can get the location and update the value of the slider :

    - (void)sliderTapped:(UIGestureRecognizer *)gestureRecognizer {
        CGPoint  pointTaped = [gestureRecognizer locationInView:gestureRecognizer.view];
        CGPoint positionOfSlider = _slider.frame.origin;
        float widthOfSlider = _slider.frame.size.width;
        float newValue = ((pointTaped.x - positionOfSlider.x) * _slider.maximumValue) / widthOfSlider;
        [_slider setValue:newValue];
    }
    

    I create an example here : https://github.com/ali59a/tap-and-slide-in-a-UISlider

提交回复
热议问题