8vius
8vius

Reputation: 5836

iOS : pan around within a view

I have the following UIPanGestureRecognizer set up:

- (void)pan:(UIPanGestureRecognizer *)gesture {
    if ((gesture.state == UIGestureRecognizerStateChanged) ||
        (gesture.state == UIGestureRecognizerStateEnded)) {
        CGPoint translation = [gesture translationInView:self.superview];
        gesture.view.center = CGPointMake(gesture.view.center.x + translation.x, gesture.view.center.y + translation.y);
        [gesture setTranslation:CGPointZero inView:self.superview];
    }
}

I want to pan around within the view, move one one place to another in the same view. What this is doing is moving the view around, how can I modify it to do what I want?

UPDATE: this is how my method ended up to pan around correctly

- (void)pan:(UIPanGestureRecognizer *)gesture {
    if ((gesture.state == UIGestureRecognizerStateChanged) ||
        (gesture.state == UIGestureRecognizerStateEnded)) {
        CGPoint translation = [gesture translationInView:self];;
        self.origin = CGPointMake(self.origin.x + translation.x, self.origin.y + translation.y);
        [gesture setTranslation:CGPointZero inView:self];
    } 
}

origin is a property in my view which just marks where the center of my graph is going to be. In its setter method there's a setNeedsDisplay to update whenever this value is changed

Upvotes: 1

Views: 5237

Answers (1)

Johannes Fahrenkrug
Johannes Fahrenkrug

Reputation: 44760

OK, so (this is just off the top of my head, untested) if you want to just scroll horizontally without using a UIScrollView, try this:

- (void)pan:(UIPanGestureRecognizer *)gesture {
    if ((gesture.state == UIGestureRecognizerStateChanged) ||
        (gesture.state == UIGestureRecognizerStateEnded)) {
        CGPoint translation = [gesture translationInView:self.superview];
        gesture.view.center = CGPointMake(gesture.view.center.x + translation.x, gesture.view.center.y);
        [gesture setTranslation:CGPointZero inView:self.superview];
    }
}

All you do is leave out the + translation.y.

If you want to use a UIScrollView (which I'd recommend), see one of these tutorials: Are there any good UIScrollView Tutorials on the net?

Upvotes: 6

Related Questions