Well, you should limit your x, y using something like this:
CGFloat maxPossibleX = CGRectGetMaxX(self.imageView.frame) - (CGRectGetWidth(sender.view.bounds)/2.0f); CGFloat maxPossibleY = CGRectGetMaxY(self.imageView.frame) - (CGRectGetHeight(sender.view.bounds) /2.0f); CGFloat minPossibleX = CGRectGetMinX(self.imageView.frame) + CGRectGetMidX(sender.view.bounds); CGFloat minPossibleY = CGRectGetMinY(self.imageView.frame) + CGRectGetMidY(sender.view.bounds); CGFloat actualX = translatedPoint.x; actualX= MAX(minPossibleX, actualX); actualX = MIN(maxPossibleX, actualX); CGFloat actualY = translatedPoint.y; actualY= MAX(minPossibleY, actualY); actualY = MIN(maxPossibleY, actualY); translatedPoint = CGPointMake(actualX, actualY);
I assume your label does not apply to your image representation here. If your shortcut is in imageView:
CGFloat maxPossibleX = CGRectGetMaxX(self.imageView.bounds) - (CGRectGetWidth(sender.view.bounds)/2.0f); CGFloat maxPossibleY = CGRectGetMaxY(self.imageView.bounds) - (CGRectGetHeight(sender.view.bounds) /2.0f); CGFloat minPossibleX = CGRectGetMidX(sender.view.bounds); CGFloat minPossibleY = CGRectGetMidY(sender.view.bounds); CGFloat actualX = translatedPoint.x; actualX= MAX(minPossibleX, actualX); actualX = MIN(maxPossibleX, actualX); CGFloat actualY = translatedPoint.y; actualY= MAX(minPossibleY, actualY); actualY = MIN(maxPossibleY, actualY); translatedPoint = CGPointMake(actualX, actualY);
Edit: I successfully tested this method in a test project:
-(void)handlePanGesture1:(UIPanGestureRecognizer *)sender { CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.imageView]; if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) { firstX = [[sender view] center].x; firstY = [[sender view] center].y; } translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y); CGFloat maxPossibleX = CGRectGetMaxX(self.imageView.bounds) - (CGRectGetWidth(sender.view.bounds)/2.0f); CGFloat maxPossibleY = CGRectGetMaxY(self.imageView.bounds) - (CGRectGetHeight(sender.view.bounds) /2.0f); CGFloat minPossibleX = CGRectGetMidX(sender.view.bounds); CGFloat minPossibleY = CGRectGetMidY(sender.view.bounds); CGFloat actualX = translatedPoint.x; actualX= MAX(minPossibleX, actualX); actualX = MIN(maxPossibleX, actualX); CGFloat actualY = translatedPoint.y; actualY= MAX(minPossibleY, actualY); actualY = MIN(maxPossibleY, actualY); translatedPoint = CGPointMake(actualX, actualY); [[sender view] setCenter:translatedPoint]; }
source share