10.2. Detecting Rotation Gestures

Problem

You want to detect when a user is attempting to rotate an element on the screen using her fingers.

Solution

Create an instance of the UIRotationGestureRecognizer class and attach it to your target view:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.helloWorldLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    self.helloWorldLabel.text = @"Hello, World!";
    self.helloWorldLabel.font = [UIFont systemFontOfSize:16.0f];
    [self.helloWorldLabel sizeToFit];
    self.helloWorldLabel.center = self.view.center;
    [self.view addSubview:self.helloWorldLabel];
    
    self.rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc]
                                      initWithTarget:self
                                      action:@selector(handleRotations:)];
    
    [self.view addGestureRecognizer:self.rotationGestureRecognizer];
    
}

Discussion

The UIRotationGestureRecognizer, as its name implies, is the perfect candidate among gesture recognizers to detect rotation gestures and to help you build more intuitive graphical user interfaces. For instance, when the user encounters an image on the screen in your application in full-screen mode, it is quite intuitive for him to attempt to correct the orientation by rotating the image.

The UIRotationGestureRecognizer class implements a property named rotation that specifies the total amount and direction of rotation requested by the user’s gesture, in radians. The rotation is determined from the fingers’ initial position (UIGestureRecognizerStateBegan) and final position (UIGestureRecognizerStateEnded).

Get iOS 7 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.