1

我有一个小的 imageView 使用 ,它在屏幕上移动UIPanGestureRecognizer,但是当它从超级视图的边缘出来时不会得到更多的触摸,因此不能再回头。如何防止图像从超级视图的边缘出现?这是代码:

- (void)pan:(UIPanGestureRecognizer *)gestureRecognizer
{
if (inLongPress) {
    UIView *hitView = [gestureRecognizer view];

    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];

    if (!(CGRectContainsRect(self.imageView.frame, hitView.frame))) {

        [UIView beginAnimations:@"" context:NULL];
        [hitView setCenter:CGPointMake(_prevCenter.x, _prevCenter.y)];
        [UIView commitAnimations];

     }
    _prevCenter=hitView.center;

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

        [hitView setCenter:CGPointMake([hitView center].x + translation.x, [hitView center].y + translation.y)];

        [gestureRecognizer setTranslation:CGPointZero inView:[hitView superview]];
    }

    if ([gestureRecognizer state] == UIGestureRecognizerStateEnded){
        inLongPress=NO;
        hitView.alpha=1.0;
    }
}

}

4

2 回答 2

2

只需使用其中的几个if将 CGPoint 限制在允许的范围内。

这样的事情确保您不能将对象移动到视图之外:

CGFloat proposedX = location.x;
CGFloat proposedY = location.y;

CGRect objectFrame = hitView.frame;
CGFloat allowedXMin = 0 + objectFrame.size.width / 2.0f;
CGFloat allowedXMax = self.view.bounds.size.width - objectFrame.size.width / 2.0f;
CGFloat allowedYMin = 0 + objectFrame.size.height / 2.0f;
CGFloat allowedYMax = self.view.bounds.size.height - objectFrame.size.height / 2.0f;

if (proposedX < allowedXMin) {
    proposedX = allowedXMin;
}
else if (proposedX > allowedXMax) {
    proposedX = allowedXMax;
}

if (proposedY < allowedYMin) {
    proposedY = allowedYMin;
}
else if (proposedY > allowedYMax) {
    proposedY = allowedYMax;
}
location = CGPointMake(proposedX, proposedY);

hitView.center = location;
于 2012-05-16T10:16:18.900 回答
2

在视图控制器的 viewDidLoad 方法中,只需将 superview 的clipsToBounds属性设置为YES

[superview setClipsToBounds:YES];

于 2012-05-16T10:12:10.537 回答