Simple UIView based Animations on the iPhone

Although for complex animation sequences on the iPhone you need to use either the OpenGL or Apple’s very own Core Animation Framework, a lot of simple animations can be achieved with the methods found in the UIView class. All these animations are actually built upon Core Animation, but they have been wrapped up for you to use with very little code.

All animations triggered by the UIView class happen within a animation block.

To start an animation block you use the UIView Class method:

+ (void)beginAnimations:(NSString *)animationID context:(void *)context;

The animation ID is used in delegate call backs for such things as the beginning and end of animation blocks. The context is an additional piece of information that can be passed through.

As both of these parameters are optional, you comenly see:

[UIView beginAnimations:@"" context:NULL];

To commit these animations, and therefore end the animation block, you need to use the UIView class method:

+ (void)commitAnimations

So what types of animations can you do ? well quite a few.

You can animate views by:

In a single animation block you can animate multiple views, and you are also able to nest animation blocks.

So lets do a common example. When a UITableViewCell is being edited you often want to make a UILabel’s (label) alpha change to 0 so it is hidden:

[UIView beginAnimations:@"" context:NULL];
[label setAlpha:(editing ? 0.0 : 1.0)];
[UIView commitAnimations];

So for the second example we also have a UILabel (label), that we want to grow when the animation code is run. We also want this animation to last 2 seconds, so the user can admire our work. In addition to this, we want the animation to “ease in”. This is known as the animation curve. The animation curves that are available are

We would do this animation using the following animation block:

[UIView beginAnimations:@"" context:NULL];

// The new frame size
[label setFrame: CGRectMake(0,0,320,100)];

// The animation duration
[UIView setAnimationDuration:2.0];

[UIView setAnimationDelay: UIViewAnimationCurveEaseIn];

[UIView commitAnimations];

This is just a brief overview of the animations you can do using the UIView class, but it should be enough to get you started. The UIView methods also include delegate call backs for when an animation starts and end. For more information see Apple’s Documentation.

If the UIView class does not have what you need, you will probably need to use the Core Animation framework. While using this framework is not trivial, it is not as hard as using OpenGL (which is used commonly for 3D games), and you can build some fantastic animations using it.