Ios – change Uislider value on tapping at particular point

iosiphoneuislider

I want to fire an action upon tapping at a particular point on UISlider by tapping, not by dragging the slider thumb.

How can I tap on a UISlider at a point to set the slider value?

A snippet of code would be appreciated.

Best Answer

    UISlider *slider = [[[UISlider alloc] init] autorelease];
…

slider setup

…
UITapGestureRecognizer *gr = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTapped:)] autorelease];
[slider addGestureRecognizer:gr];
- (void)sliderTapped:(UIGestureRecognizer *)g {
     UISlider* s = (UISlider*)g.view;
    if (s.highlighted)
        return; // tap on thumb, let slider deal with it
    CGPoint pt = [g locationInView: s];
    CGFloat percentage = pt.x / s.bounds.size.width;
    CGFloat delta = percentage * (s.maximumValue - s.minimumValue);
    CGFloat value = s.minimumValue + delta;
    [s setValue:value animated:YES];
}
Related Topic