开发者

How to prevent user from panning my view off screen?

I've got a UIView that receives user panning from a gesture recognizer. I realized some times user would "throw" my view almost out of screen and that looks very bad. I want to prevent this from happening. I know I should do some check in my selector, but I don't know how to do it when the view is translated.

Here is my code:

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

    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];

    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        CGPoint translation = [gestureRecognizer translationInView:[piece supervie开发者_运维技巧w]];

        [piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y + translation.y)];
        [gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
    }


}

Thanks in advance

Regards

Leo


You can add following condition in you code.

if([gestureRecognizer state] == UIGestureRecognizerStateEnd)

Inside that you can check weather any corner of view is outside of screen or not. If its is outside then you can bounce it back inside screen.

Following is a possible example.

if (zl.layer.frame.origin.x > 0) {
    self.moveFactorX = self.moveFactorX-zl.layer.frame.origin.x; 
    [zl.layer setValue:[NSNumber numberWithFloat: moveFactorX+totalMoveX] forKeyPath: @"transform.translation.x"];
}
else if(zl.layer.frame.origin.x < pageSize.width - zl.layer.frame.size.width){
    self.moveFactorX = self.moveFactorX-(zl.layer.frame.origin.x - pageSize.width + zl.layer.frame.size.width); 
    [zl.layer setValue:[NSNumber numberWithFloat: moveFactorX+totalMoveX] forKeyPath: @"transform.translation.x"];
}

This checked for me weather left side of layer of zl class is inside the screen. When It is inside screen then i was pushing is back to left most corner.

In else it checks weather it is inside the screen from right side or not. and when condition satisfies it will push it to right border.

Same way you have to implement for top and bottom also.

If you find code confusing then post here. I will modify it accordingly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜