Cover by Vandad Nahavandipoor

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

8.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.view.backgroundColor = [UIColor whiteColor];  
  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 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required