O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

20.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 20.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 20.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 20-9), 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 5 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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required