Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone:Programming UISlider to position at clicked location

How to set the slider to clicked position and get the slider value on the clicked location on UISlider in iPhone programming. i know we can drag the slider to that position but i dont want to do it. Can you please tel me how to set the slider to clicked position? Is this possible to do?

like image 658
suse Avatar asked May 24 '10 06:05

suse


2 Answers

Here is the part "left as a user exercise":

- (void) tapped: (UITapGestureRecognizer*) 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];
}
like image 50
matt Avatar answered Oct 04 '22 22:10

matt


The way I did it is to subclass the slider and check in touchesBegan. If the user taps on the thumb button area (which we track) then ignore the tap, but any where else on the trackbar we do: :

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self];

    // if we didn't tap on the thumb button then we set the value based on tap location
    if (!CGRectContainsPoint(lastKnownThumbRect, touchLocation)) {

        self.value = self.minimumValue + (self.maximumValue - self.minimumValue) * (touchLocation.x / self.frame.size.width);
    }

    [super touchesBegan:touches withEvent:event];
}

- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value {

    CGRect thumbRect = [super thumbRectForBounds:bounds trackRect:rect value:value];
    lastKnownThumbRect = thumbRect;
    return thumbRect;
}
like image 25
peterept Avatar answered Oct 04 '22 23:10

peterept