Assignment #3 Task #7

Please note, this blog entry is from a previous course. You might want to check out the current one.

Support the following gestures inside your graphing view:

  • Pinching (adjusts your view’s scale).
  • Panning (moves the entire graph, including axes, to follow the touch around).
  • Triple-tapping (moves the origin of the graph to the point of the triple-tap).

We add the actual functions to the view, where we

  • adjust the scale of the data source when we pinch,
  • adjust the origin of the data source when we pan or center.

- (void)pinch:(UIPinchGestureRecognizer *)gesture
{
    if ((gesture.state != UIGestureRecognizerStateChanged) &&
        (gesture.state != UIGestureRecognizerStateEnded)) return;
    self.dataSource.scale *= gesture.scale;
    gesture.scale = 1;
}

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

- (void)center:(UITapGestureRecognizer *)gesture
{
    if (gesture.state != UIGestureRecognizerStateEnded) return;
    CGPoint location = [gesture locationInView:self];
    self.dataSource.origin = location;
}

and setup the gesture recognizers in setGraphView:

    [graphView addGestureRecognizer:[[UIPinchGestureRecognizer alloc] 
        initWithTarget:self.graphView action:@selector(pinch:)]];
    [self.graphView addGestureRecognizer:[[UIPanGestureRecognizer alloc] 
        initWithTarget:self.graphView action:@selector(pan:)]];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] 
        initWithTarget:self.graphView action:@selector(center:)];
    tap.numberOfTapsRequired = 3;
    [self.graphView addGestureRecognizer:tap];    

To see the change we need to updated the views:

- (void)setScale:(CGFloat)scale
{
    if (scale == _scale) return;
    _scale = scale;
    [self.graphView setNeedsDisplay];
}

- (void)setOrigin:(CGPoint)origin
{
    if (CGPointEqualToPoint(origin, _origin)) return;
    _origin = origin;
    [self.graphView setNeedsDisplay];
}
FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

Leave a Reply

Your email address will not be published.