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;
}
}
}
just use a couple of
ifthat limit the CGPoint to an allowed range.Something like this makes sure that you can’t move the object outside of the view: