UIPanGestureRecognizer limit to coordinates
First, you need to enforce the limit before you change the view's center. Your code changes the view's center before checking if the new center is out of bounds.
Second, you need to use the correct C operators for testing the Y coordinate. The =
operator is assignment. The ==
operator tests for equality, but you don't want to use that either.
Third, you probably don't want to reset the recognizer's translation if the new center is out-of-bounds. Resetting the translation when the drag goes out of bounds will disconnect the user's finger from the view he's dragging.
You probably want something like this:
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
// Figure out where the user is trying to drag the view.
CGPoint newCenter = CGPointMake(self.view.bounds.size.width / 2,
recognizer.view.center.y + translation.y);
// See if the new position is in bounds.
if (newCenter.y >= 160 && newCenter.y <= 300) {
recognizer.view.center = newCenter;
[recognizer setTranslation:CGPointZero inView:self.view];
}
}
There's probably an unintended consequence of Rob's answer. If you drag fast enough the newCenter will be out of bounds but that could happen before the last update. That'll result in the view not being panned all the way to the end. Instead of not updating if the newCenter is out of bounds, you should always update the center but limit the bounds like so:
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
// Figure out where the user is trying to drag the view.
CGPoint newCenter = CGPointMake(self.view.bounds.size.width / 2,
recognizer.view.center.y + translation.y);
// limit the bounds but always update the center
newCenter.y = MAX(160, newCenter.y);
newCenter.y = MIN(300, newCenter.y);
recognizer.view.center = newCenter;
[recognizer setTranslation:CGPointZero inView:self.view];
}