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{[superviewDidAppear:paramAnimated];self.xcodeImageView.center=self.view.center;/* Begin the animation */[UIViewbeginAnimations:@"clockwiseAnimation"context:NULL];/* Make the animation 5 seconds long */[UIViewsetAnimationDuration:5.0f];[UIViewsetAnimationDelegate:self];[UIViewsetAnimationDidStopSelector:@selector(clockwiseRotationStopped:finished:context:)];/* Rotate the image view 90 degrees */self.xcodeImageView.transform=CGAffineTransformMakeRotation((90.0f*M_PI)/180.0f);/* Commit the animation */[UIViewcommitAnimations];}
We’ve chosen the clockwiseRotationStopped:finished:context: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access