Home / iPhone Tips and Tutorials

Animating a View

Whenever you assign a new value to certain view properties (such as the frame, center, and bounds properties, as explained in the previous section), the view is immediately redrawn and the change is immediately visible on the screen.

In addition, changes to several view properties (such as those just mentioned) can be animated. This means that changing the property creates an animation that conveys the change to the user over a short period of time - and it's all handled for you by the UIView class. What's more, it takes only one method call to specify the animations to be performed and the options for the animation.

The following properties of the UIView class are animatable (the first three are explained previously):

  • frame
  • bounds
  • center
  • transform: Explained later in the article.
  • alpha: The degree of transparency. If you animate it, you can get views to fade in and fade out.
  • backgroundColor: Allows you to transition from one color to another.
  • contentStretch: Controls how a view's content is stretched to fill its bounds when the view is resized and is often used to animate the resizing of a buttons and controls.

More Code

In this section, you add the code to animate the car and have it travel up the screen, turn around, travel back down the screen, and then turn around again so that it's back to its original position. First you declare some methods. Add the bolded code in Listing-1 to RTViewController.h.

Listing-1: Updating the RTViewController.h interface with the Methods to Animate the Car

#import <UIKit/UIKit.h>

@interface RTViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIImageView *car;
@property (weak, nonatomic) IBOutlet UIButton
	   *testDriveButton;
@property (weak, nonatomic) IBOutlet UIImageView
	   *backgroundImage;

- (IBAction)testDrive:(id)sender;
- (void)rotate;
- (void)returnCar;
- (void)continueRotation;

@end
[Contents] [Next]