Search code examples
iosgestures

reset an iOS gesture by button click


I have an application that allows a user to pan and zoom in on an image. I think that, without too much trouble, the user can get themselves into a state where they are zoomed in to one portion of the image, and would want to reset everything back to the 'ground state' (ie, bring all the translation and rescaling back to 0 and 1, respectively).

I'm doing translation by:

- (void)panGestureRecognized:(UIPanGestureRecognizer *)recognizer
{
  CGPoint translation = [recognizer translationInView:self.view];
  recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                   recognizer.view.center.y + translation.y);
  [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}

And this works fine, I can translate the image.

If I press the button, I want to be able to change the translation back to 0,0. One way to do this would seem to be to store the gesturerecognizer and set that back to zero, as in:

mPanRecognizer.view.center = CGPointMake(mPanRecognizer.view.center.x,
                                   mPanRecognizer.view.center.y);
[mPanRecognizer setTranslation:CGPointMake(0,0) inView:self.view];

Where mPanRecognizer is a member variable storing the recognizer. However, doing this produces the following log information, with no actual behavioral change:

Ignoring call to [UIPanGestureRecognizer setTranslation:inView:] since gesture recognizer is not active.

So how can I reset the gesture to be translating to 0,0 by pressing a button?


Solution

  • This can be done without using gesture recognizers. To set the scaling, use

    [self.view setBound:CGRectMake(0,0,width,height)];
    

    where width and height are the dimensions of your device.

    To set the translation, use

    [self.view setCenter:CGPointMake(width/2.0,height/2.0)];
    

    To set your width and height easily, contain your view in a separate UIView. Have that UIView anchored properly and in the proper z-order, then you can modify the above lines to be

    [imageView setBounds:CGRectMake(0,0,imageView.superview.bounds.size.width,imageView.superview.bounds.size.height)];
    [imageView setCenter:CGPointMake(imageView.superview.center.x, imageView.superview.center.y)];
    

    thereby avoiding the need for storying of any points or magic numbers specific to a particular device.