adit
adit

Reputation: 33644

limiting the panning bounds of UIPanGestureRecognizer

I have a view that I am currently hiding at the bottom of the screen. Now I want to be able to move the view by scrolling it vertically, through the y-axis. But I don't want it to go up further than full height of the view (i.e: I don't want to see a white space at the bottom). I've written this code:

- (IBAction)panHighlightReadingVC:(UIPanGestureRecognizer *)recognizer
{
    CGPoint translation = [recognizer translationInView:self.view];

    CGPoint newCenter = CGPointMake(self.view.bounds.size.width / 2,
                                    roundf(recognizer.view.center.y + translation.y));

    CGFloat velocityY = [recognizer velocityInView:self.view].y;
    if ((recognizer.view.frameY > self.view.frameHeight - recognizer.view.frameHeight || velocityY > 0)) {
        recognizer.view.center = newCenter;
        [recognizer setTranslation:CGPointZero inView:self.view];
    } 
}

This sort of work, if I scroll it slowly. If I scroll it very fast, then there is a chance that the frameY of the view is less than the `superView.frameHeight - recognizer.view.frameHeight. How do I fix this?

Upvotes: 0

Views: 1425

Answers (1)

Kekoa
Kekoa

Reputation: 28240

When you are calculating the newCenter, limit it to the bounds that you actually want it to fit in. You probably don't need that last if statement if you are limiting the newCenter to be within your limits.

Also, do yourself a favor and only use center when it actually makes things simpler. In your case I think you should use frame. Then you don't have to worry about dividing by 2.

Try something like this:

- (IBAction)panHighlightReadingVC:(UIPanGestureRecognizer *)recognizer
{
    CGPoint translation = [recognizer translationInView:self.view];

    CGFloat newY = MAX(recognizer.view.frame.origin.y + translation.y, self.view.frameHeight - recognizer.view.frameHeight);

    CGRect newFrame = CGRectMake(recognizer.view.frame.origin.x, newY, recognizer.view.frame.size.width, recognizer.view.frame.size.height);

    recognizer.view.frame = newFrame;
    [recognizer setTranslation:CGPointZero inView:self.view];
}

Also, velocity doesn't seem to apply in your situation, it only complicates things.

Upvotes: 1

Related Questions