17.16. Animating and Rotating Views

Problem

You want to animate the rotation of your views.

Solution

Create a rotation affine transform and use the animation methods of UIView to animate the rotation.

Discussion

Note

I highly recommend that you read Recipe 17.14 before proceeding with this section of the book.

In order to rotate a view while animating it, you must apply a rotation transformation to it while in an animation block (see Recipe 17.12). Let’s have a look at some sample code that will make this clearer. Let’s say we have an image named Xcode.png (see Figure 17-14), and we want to display it in the center of the screen. After the image is displayed, we want to rotate it 90 degrees over a five-second time period and then rotate it back to its original orientation. So when the view appears on the screen, let’s rotate the image view 90 degrees clockwise:

- (void) viewDidAppear:(BOOL)paramAnimated{
  [super viewDidAppear:paramAnimated];

  self.xcodeImageView.center = self.view.center;

  /* Begin the animation */
  [UIView beginAnimations:@"clockwiseAnimation"
                  context:NULL];

  /* Make the animation five seconds long */
  [UIView setAnimationDuration:5.0f];

  [UIView setAnimationDelegate:self];

  [UIView setAnimationDidStopSelector:
   @selector(clockwiseRotationStopped:finished:context:)];

  /* Rotate the image view 90 degrees */
  self.xcodeImageView.transform =
  CGAffineTransformMakeRotation((90.0f * M_PI) / 180.0f);  
  
  /* Commit the animation */
  [UIView commitAnimations];

}

We’ve chosen the clockwiseRotationStopped:finished:context: ...

Get iOS 6 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.