CHwang CHwang - 1 month ago 7x
Objective-C Question

UISlider thumb moving without touching thumb

I am using UISlider in my project. Normally, thumb should move as soon as we touch and drag the thumb. But, in my case, thumb moved while I touched on the edge of it without touching it. Like this:

enter image description here

Here is my code:

self.slider = [[UISlider alloc] initWithFrame:CGRectMake(30, [UIScreen mainScreen].bounds.size.height - 200, [UIScreen mainScreen].bounds.size.width-30, 30)];
[self.view addSubview:self.slider];

Why the thumb moved and how to deal with it? My target is that, thumb will move only if I thouch and drag it, and will not move when I touched on the edge of it.


For that you need to use taoGesture with UISlider, so first add UITapGestureRecognizer in your slider object then set its value in action method of selector of gestureRecognizer.

Add following code after you have added slider in your View.

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onSliderTap:)];
[self.slider addGestureRecognizer:tapGestureRecognizer];

Now in onSliderTap you can get the location point then update the value of the slider

- (void)onSliderTap:(UITapGestureRecognizer *)recognizer {
    float width = self.slider.frame.size.width;
    CGPoint point = [recognizer locationInView:recognizer.view];
    CGFloat sliderX = self.slider.frame.origin.x;
    float newValue = ((point.x - sliderX) * self.slider.maximumValue) / width;
    [self.slider setValue:newValue];