Animating Views

Implementing animations in your app is incredibly easy. In this tutorial we'll move a image over the screen using animation.

Update: Oct 6, 2014. The rewritten version in Swift for iOS 8 and Xcode 6 is available here.

Open Xcode and create a new Single View Application. For product name, use AnimatingViewDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards checkbox is deselected and Use Automatic Reference Counting checkbox is selected.

For this project we'll need a image to let it animate. Download the iOS 6 Logo here and unpack and add this file to the project.  Go to ViewController.m and add a property in the @interface section.

@property (nonatomic, strong) UIImageView *imageView;

This property will contain our image.In ViewController.m change ViewDidLoad in

- (void)viewDidLoad 
[super viewDidLoad];

UIImage *image = [UIImage imageNamed:@"ios6.jpeg"];
self.imageView = [[UIImageView alloc] initWithImage:image];

self.imageView.frame = CGRectMake(0, 0, 100.0f, 100.0f);
[self.view addSubview:self.imageView];

self.view.backgroundColor = [UIColor whiteColor];

Our image is loaded into the main view and placed in the upper left corner. Add the viewDidAppear method.

- (void)viewDidAppear:(BOOL)animated 
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:3.0f];

self.imageView.frame = CGRectMake(200.0f, 200.0f, 100.0f, 100.0f);

[UIView commitAnimations];

In viewDidAppear we'll specify the animation code.It uses beginAnimations:context to start an animation block. The animation is set with a duration of 3.0 seconds. Then the frame of the image view is set to their final destination, and you call commitAnimations to start the animations. Build and Run, you should see the image animating to the bottom right.

You can download the source code of the AnimatingViewDemo at the ioscreator repository on github.