iOS add Rotation gesture along with Pinch/Zoom

soleil picture soleil · Aug 16, 2012 · Viewed 11.5k times · Source

I am setting up my recognizers like this. Note that although I'm adding the recognizers to self.view, it is actually self.container that is getting transformed (which is a subview).

UIPinchGestureRecognizer *twoFingerPinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(twoFingerPinch:)];
twoFingerPinch.delegate = self;
[self.view addGestureRecognizer:twoFingerPinch];

UIRotationGestureRecognizer *rotate = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotate:)];
rotate.delegate = self;
[self.view addGestureRecognizer:rotate];

The pinch/zoom works fine on it's own:

- (void)twoFingerPinch:(UIPinchGestureRecognizer *)recognizer 
{

CGFloat scale = _lastScale * recognizer.scale;

CGAffineTransform tr = CGAffineTransformScale(self.view.transform, scale, scale);
self.container.transform = tr;

if (recognizer.state == UIGestureRecognizerStateEnded)  {
    _lastScale = scale;
    return;
}
}

However I'm having a hard time adding the rotation:

- (IBAction)handleRotate:(UIRotationGestureRecognizer *)recognizer {
//recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);
//recognizer.rotation = 0;

CGFloat rotation = _lastRotation * recognizer.rotation;

self.container.transform = CGAffineTransformRotate(self.view.transform, recognizer.rotation);
recognizer.rotation = 0;

if (recognizer.state == UIGestureRecognizerStateEnded)  {
    _lastRotation = rotation;
    return;
}
}

When I add the rotation recognizer, the rotation works but the pinch/zoom is broken (jumps haphazardly from really small to large). How can I resolve this so that they both work?

Answer