禁用平移手势是否出界的检测(Disabling Pan Gesture if out of boun

2019-08-04 03:09发布

我有一个UIView我试图上下移动画面,但我只希望以使其能够移动,这样您不能拖动视图下来的时候它是在其正常位置(0,0)

我试图检测时,识别器的中心是不是视图的高度的一半,但是观点是那么不可移动,中心始终高度的一半(230在这种情况下)。

有任何想法吗?

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

Answer 1:

而不是手动计算所述点是否视图的边界内,使用CGRectContainsPoint(rect, point) 。 这对我来说是什么工作,我喜欢它,因为它是短,更具可读性:

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.
        }
}


Answer 2:

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


Answer 3:

尝试

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


Answer 4:

recognizer.view.center = CGPointMake(recognizer.view.center.x, MAX(recognizer.view.center.y + translation.y, ([[UIScreen mainScreen] bounds].size.height - 20)/2));


文章来源: Disabling Pan Gesture if out of bounds detected