限制UIPanGestureRecognizer的平移范围

时间:2012-12-19 18:13:32

标签: iphone objective-c ios ipad

我认为我目前正躲在屏幕的底部。现在我希望能够通过y轴垂直滚动来移动视图。但我不希望它超过视图的整个高度(即:我不想在底部看到一个白色空间)。我写了这段代码:

- (IBAction)panHighlightReadingVC:(UIPanGestureRecognizer *)recognizer
{
    CGPoint translation = [recognizer translationInView:self.view];

    CGPoint newCenter = CGPointMake(self.view.bounds.size.width / 2,
                                    roundf(recognizer.view.center.y + translation.y));

    CGFloat velocityY = [recognizer velocityInView:self.view].y;
    if ((recognizer.view.frameY > self.view.frameHeight - recognizer.view.frameHeight || velocityY > 0)) {
        recognizer.view.center = newCenter;
        [recognizer setTranslation:CGPointZero inView:self.view];
    } 
}

这种工作,如果我慢慢滚动它。如果我非常快地滚动它,那么视图的frameY可能小于`superView.frameHeight - recognizer.view.frameHeight。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

在计算newCenter时,将其限制为您真正希望它适合的范围。如果您将newCenter限制在限制范围内,则可能不需要最后一条if语句。

另外,帮自己一个忙,只有在实际上让事情更简单时才使用中心。在你的情况下,我认为你应该使用框架。然后你不必担心除以2。

尝试这样的事情:

- (IBAction)panHighlightReadingVC:(UIPanGestureRecognizer *)recognizer
{
    CGPoint translation = [recognizer translationInView:self.view];

    CGFloat newY = MAX(recognizer.view.frame.origin.y + translation.y, self.view.frameHeight - recognizer.view.frameHeight);

    CGRect newFrame = CGRectMake(recognizer.view.frame.origin.x, newY, recognizer.view.frame.size.width, recognizer.view.frame.size.height);

    recognizer.view.frame = newFrame;
    [recognizer setTranslation:CGPointZero inView:self.view];
}

此外,速度似乎并不适用于您的情况,它只会使事情变得复杂。