1

I want to know if there is a way to bound the movement of my UIView within its superview while using GestureRecognizer.

eg. I have a UIImageview To whom I add UIPanGestureRecognizer with action panPiece. I adjust its center in the following way to avoid its movement out of its superview. But it doesnt work properly.

-(CGPoint) centerWithBounds:(CGPoint)center andViewFrame:(CGRect)viewFrame andBoundingFrame:(CGRect)boundingFrame{

 CGFloat lowerXBound  = boundingFrame.origin.x + ( viewFrame.size.width/2 );
 CGFloat higherXBound = boundingFrame.origin.x + boundingFrame.size.width - ( viewFrame.size.width/2 );

 CGFloat lowerYBound  = boundingFrame.origin.y + ( viewFrame.size.height/2 );
 CGFloat higherYBound = boundingFrame.origin.y + boundingFrame.size.height - ( viewFrame.size.height/2 );

 if ( center.x < lowerXBound) {
  center.x = lowerXBound;
 }
 if ( center.x > higherXBound ){
  center.x = higherXBound;
 }
 if ( center.y < lowerYBound) {
  center.y = lowerYBound;
 }
 if ( center.y > higherYBound ){
  center.y = higherYBound;
 }

 return center;
}

- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
    UIView *piece = [gestureRecognizer view];

    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];

    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        CGPoint translation = [gestureRecognizer translationInView:[piece superview]];
        CGPoint translatedCenter = CGPointMake([piece center].x + translation.x, [piece center].y + translation.y);
  CGPoint center = [self centerWithBounds:translatedCenter andViewFrame:[piece frame] andBoundingFrame:[[piece superview] frame]];
        [piece setCenter:center];
        [gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
    }
}

Code help is appreciated.

rkb
  • 10,933
  • 22
  • 76
  • 103

2 Answers2

1

You just need to use the property clipsToBounds (set it to YES) to the superview. Had the same issue earlier. Works perfectly after that.

Joel Joseph
  • 192
  • 1
  • 1
  • 9
-1

Perhaps it is because

standard UIImageViews, despite being UIView subclasses, do not react to gesture recognizer added to them

working with uigesturerecognizers

mracoker
  • 886
  • 9
  • 14