使用UIPanGestureRecognizer时设置可拖动UIView的位置限制

时间:2012-02-17 00:16:16

标签: iphone uigesturerecognizer

这个问题与我最近发表的这篇文章有一些关系:Drag a UIView part-way, then it moves on its own

简而言之,我有一个可拖动的UI视图,在窗口底部部分可见。用户可以使用“拉片”在屏幕上向上或向下拖动视图。我已经使用此代码对上部和下部位置的Y位置设置了限制,但我不知道这是否是正确的方法:

- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
    UIView *piece = [gestureRecognizer view];
    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];

    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged)
    {
        CGPoint velocity = [gestureRecognizer velocityInView:[piece superview]];
        CGPoint translation = [gestureRecognizer translationInView:[piece superview]];

        if(velocity.y < 0)  //user is dragging the view upwards the screen
        {
            // Set the maximum Ypos as the top 1/3rd of the screen
            CGFloat maxYPos = self.view.frame.size.height/3;
            if(blogTextView.frame.origin.y >= maxYPos)
            {
                [piece setCenter:CGPointMake([piece center].x, [piece center].y + translation.y)];
                [gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
            }
        }
        else
        {
            // User is dragging the view downwards the screen
            // Set the lowest Y position to be 420
            if(blogTextView.frame.origin.y <= 420) //size of remaining view
            {
                [piece setCenter:CGPointMake([piece center].x, [piece center].y + translation.y)];
                [gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
            }
        }
    }

}

我认为这看起来很难看,但如果用户正在慢慢拖动视图,它就会起作用。问题是如果用户非常快速地向上或向下拖动视图,那么视图可以超出我放在Y位置的限制。例如,在底部有可拖动视图的默认状态下,我能够以类似快照的速度将视图一直拖到导航栏上!

是否有正确的方法来设置拖动视图的限制,并在此gestureRecognizer回调中正确处理?

供参考,以下是测试应用程序的图片:

Default screen with draggable view at the bottom and the pull tab

View dragged up to its correct max Y position

谢谢!

1 个答案:

答案 0 :(得分:2)

问题在于以下代码:

if(blogTextView.frame.origin.y >= maxYPos)
{
    [piece setCenter:CGPointMake([piece center].x, [piece center].y + translation.y)];
    [gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
}

这一个:

if(blogTextView.frame.origin.y <= 420) //size of remaining view
{
    [piece setCenter:CGPointMake([piece center].x, [piece center].y + translation.y)];
    [gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
}

您应该使用blogTextView.frame.origin.y的未来值(如果您在if bloc中执行代码,则会获得该值。)

换句话说,您总是在做额外的翻译。你不能注意到拖动时因为额外的翻译并不重要,但是在快速拖动时会变得很重要,你会发现错误的结果。