0

I am currently moving a UIImageView using a UIPanGestureRecognizer object in my app. At present, this UIImageView is moving up and down very nicely on my screen. However, what I would like to do now is restrict the boundary of the UIImageView's movement to within the region covered by my UITableView that resides in the middle of the screen. I want to restrict this movement to both the upper, and lower borders of the UITableView. Here is my relevant method where I control the movement of my UIImageView:

- (void)panGestureDetected:(UIPanGestureRecognizer *)recognizer {

    _startLocation = [recognizer locationInView:_imageView];

    NSLog(@"The point is: %d", _startLocation);

    CGPoint newCenter  = _imageView.center;

    newCenter.y = [recognizer locationInView:[_imageView superview]].y;
//this is where I figure I need to include an if statement to perform a check to see if the location is within the desired region

    _imageView.center = newCenter;


}

I realize that I will need to include an "if" statement within my method to check to see if my UIImageView is within my desired region, but the problem is that I am not sure how to check for this. Can someone help me out here?

syedfa
  • 2,801
  • 1
  • 41
  • 74

1 Answers1

0

You should be using the translationInView method (documentation).

This will return a CGPoint of location the user move the image to. Compare the original position of the image view to the translation. If the translation is too large such that the image view would move outside of the desired region, don't move it.

The code should look something like this (I think you might be able to just drop this right in):

CGPoint translation = [recognizer translationInView:_imageView.superview];
[recognizer setTranslation:CGPointMake(0, 0) inView:_imageView.superview];

CGPoint center = recognizer.view.center;
center.y += translation.y;
if (center.y < _table.frame.origin.y 
    || center.y > _table.frame.size.height) {
           return;
}
recognizer.view.center = center;

See this question for an alternate implementation.

Community
  • 1
  • 1
Austin
  • 195
  • 2
  • 9
  • Thanks so much for your solution. I do have a follow up question for you. My table view (_table), and my UIImageView (_imageView) are both attached to the parent/super view. Because of this, do I replace _imageView.superview with _table? – syedfa Jun 20 '13 at 19:54
  • I would replace _imageView.superview.frame.origin.y with _table.frame.origin.y and _imageView.frame.size.height with _table.frame.size.height. Let me know if that works – Austin Jun 20 '13 at 21:05