change Uislider value on tapping at particular point

Ronak picture Ronak · May 16, 2012 · Viewed 6.9k times · Source

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.

Answer

Ronak picture Ronak · May 17, 2012
    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];
}