简体   繁体   English

使用UIPanGestureRecognizer

[英]Use of UIPanGestureRecognizer

I have a small imageView that moves on the screen using the UIPanGestureRecognizer , but when it comes out from the edges of the superview does not get more touches and therefore can no longer turn back. 我有一个小的UIPanGestureRecognizer使用UIPanGestureRecognizer在屏幕上移动,但是当它从UIPanGestureRecognizer视图的边缘出来时没有得到更多的触摸,因此无法再回头。 How can I prevent that the image comes out from the edges of the superview? 如何防止图像从超视图的边缘出来? This is the code: 这是代码:

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

} }

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

[superview setClipsToBounds:YES];

just use a couple of if that limit the CGPoint to an allowed range. if将CGPoint限制在允许的范围内,只需使用几个。

Something like this makes sure that you can't move the object outside of the view: 这样的东西确保你不能将对象移动到视图之外:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM