Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling Pan Gesture if out of bounds detected

I have a UIView I am trying to move up and down the screen, however I only wish to enable it to pan so that you cannot drag the view down when it is in its normal position (0, 0)

I tried to detect when the recognizer's center is not half the height of the view, however the view is then immovable, and the center is always half the height (230 in this case).

Any ideas?

- (IBAction)panDetected:(UIPanGestureRecognizer *)recognizer {
    CGPoint translation = [recognizer translationInView:self.view];
    NSLog(@"\ncenter.y: %f\ntranslation.y: %f\n", recognizer.view.center.y, translation.y);
    if (recognizer.view.center.y > ([[UIScreen mainScreen] bounds].size.height - 20)/2) {
            return;
    }
    recognizer.view.center = CGPointMake(recognizer.view.center.x,
                                         recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
like image 602
Alex Muller Avatar asked Oct 06 '22 16:10

Alex Muller


1 Answers

Instead of manually computing whether the points are within the view's bounds, use CGRectContainsPoint(rect, point). This is what works for me, and I like it because it's shorter and more readable:

func handlePan(pan: UIPanGestureRecognizer) {
    switch pan.state {
    case .Began:
        if CGRectContainsPoint(self.pannableView.frame, pan.locationInView(self.pannableView)) {
            // Gesture started inside the pannable view. Do your thing.
        }
}
like image 76
MLQ Avatar answered Oct 10 '22 04:10

MLQ