Disabling Pan Gesture if out of bounds detected

2019-03-30 02:56发布

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];
}

4条回答
Bombasti
2楼-- · 2019-03-30 03:12
recognizer.view.center = CGPointMake(recognizer.view.center.x, MAX(recognizer.view.center.y + translation.y, ([[UIScreen mainScreen] bounds].size.height - 20)/2));
查看更多
Viruses.
3楼-- · 2019-03-30 03:15

try

CGPoint translation = [recognizer translationInView:self.view];  
if (translation.x+recognizer.view.frame.origin.x<0||translation.y+recognizer.view.frame.origin.y<0)
    {
        return;
    }

 recognizer.view.center = CGPointMake(recognizer.view.center.x,
                                     recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
查看更多
▲ chillily
4楼-- · 2019-03-30 03:22

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.
        }
}
查看更多
Bombasti
5楼-- · 2019-03-30 03:24
CGPoint translation = [recognizer translationInView:self.view];
CGPoint finalpoint = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y+ translation.y);

//limit the boundary    
if ((recognizer.view.frame.origin.x>0 && translation.x > 0) || (recognizer.view.frame.origin.x + recognizer.view.frame.size.width<=320 && translation.x < 0))
    finalpoint.x = recognizer.view.center.x;

if ((recognizer.view.frame.origin.y>0 && translation.y > 0) || (recognizer.view.frame.origin.y + recognizer.view.frame.size.height<=self.view.frame.size.height && translation.y < 0))
    finalpoint.y = recognizer.view.center.y;

//set final position
recognizer.view.center = finalpoint;
[recognizer setTranslation:CGPointZero inView:self.view];
查看更多
登录 后发表回答