Domanda

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

}

È stato utile?

Soluzione

just use a couple of if that limit the CGPoint to an allowed range.

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;

Altri suggerimenti

In your viewDidLoad method of your view controller , just set the clipsToBounds property of your superview to YES.

[superview setClipsToBounds:YES];

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top