Simple iPhone Animation Tutorial

The learning curve of Cocoa can be steep depending on your background, but it’s a climb that is sure to leave a smile on your face every few steps of the way. Just enough to offset the hair pulling and cursing that is sure to ensue from jumping into Cocoa programming for the first time. One of the features that sweetened things up for me was Cocoa’s UIView animation capabilities. There is a lot to cover, and I just don’t have the time to even think about how to approach a lesson on all the animation features. I will give you an example of basic animation and a possible implementation and point you in the direction of Apple’s documentation so that you can build upon what you learned here.

For more information make sure to read Apple’s documentation on the UIView class. There is a lot more you can do with but let this be simply a foundation for you to learn the basic concept.



We will be building a simple application that contains two views. The first view contains a button labeled “Show” that when clicked will cause a second view to scroll down and overlap the first view and take up half the screen. The button will change it’s label to “Hide” and when clicked will cause the second view to scroll off screen.

In Xcode, create a new project (File -> New Project) and make sure it is a View-based application. Name it something like “ViewAnimationDemo” and click the “Save” button:


Create a new View-based application in Xcode



Double-click the View Controller Nib file to open it in Interface Builder:

Double-click the View Controller nib file to open it in Interface Builder



In Interface Builder, select a Round Rect Button from the Library and drag it to our View. Change the button Title to “Show.”

Drag a button to the view

Change the button Title to "Show"



Save your work and go back into Xcode. We will need to create an IBOutlet to change the button Title and IBAction to create the animation. Open your view controller header file and paste this code:

#import <UIKit/UIKit.h>
 
@interface ViewAnimationDemoViewController : UIViewController {
	IBOutlet UIButton *showHideButton; // outlet to allow us access to our button label
	UIImageView *imageView; // This is the subview we will show/hide
	BOOL viewVisible; // Will be YES if our imageView is visible, NO otherwise.
}
 
- (IBAction)onButtonClick:(id)sender; // IBAction handler for our button click
- (void)showHideView; // Our code to show/hide and animate our imageView will be here
 
@property (nonatomic, retain) IBOutlet UIButton *showHideButton;
@property (nonatomic, retain) UIImageView *imageView;
 
@end

You can now go back into Interface Builder and connect all the loose ends. Ctrl-Click-Drag from your button to File’s Owner and select “onButtonClick” then do the same in reverse and select “showHideButton.”


Ctrl-Click-Drag from the button to File's Owner

Now select "showHideButton" and when you are done do the same in reverse by dragging from File's Owner to the button but selecting "onButtonClick."


Now on to the good stuff. In your view controller implementation, synthesize your properties:

@synthesize showHideButton, imageView;

Add a viewDidLoad method and create our imageView. We will set it up and off screen for now. (The images for this project are in the source code .zip file at the bottom of the tutorial.)

- (void)viewDidLoad {
    [super viewDidLoad];
 
	UIImage *guns = [UIImage imageNamed:@"guns.png"]; // load our image resource
	imageView = [[UIImageView alloc] initWithImage:guns]; // Init our UIImageView with our image
	[self.view addSubview:imageView]; // Add it as a subview of our main view
	[imageView setFrame:CGRectOffset([imageView frame], 0, -imageView.frame.size.height)]; // Move it up top and off screen
	viewVisible = NO;
}

Create the onButtonClick action and our showHideView method. As you can see, there are two lines that may be very unfamiliar to you. The beginAnimations and commitAnimations are sandwiching our code that moves our imageView on and off screen. When placed around code to move a UIView the view will slide into place instead of just appearing out of nowhere.

- (IBAction)onButtonClick:(id)sender {
	[self showHideView]; // Show and hide our imageView in an animated fashion
}
 
- (void)showHideView {
	if (viewVisible) { // If our imageView is on screen hide the view
		[UIView beginAnimations:@"animateImageOff" context:NULL]; // Begin animation
		[imageView setFrame:CGRectOffset([imageView frame], 0, -imageView.frame.size.height)]; // Move imageView off screen
		[UIView commitAnimations]; // End animations
		viewVisible = NO;
		[showHideButton setTitle:@"Show" forState:UIControlStateNormal]; // Change button title to "Show"
	} else { // if our imageView is off screen show the view
		[UIView beginAnimations:@"animateImageOn" context:NULL]; // Begin animation
		[imageView setFrame:CGRectOffset([imageView frame], 0, imageView.frame.size.height)]; // Move imageView on screen
		[UIView commitAnimations]; // End animations
		viewVisible = YES;
		[showHideButton setTitle:@"Hide" forState:UIControlStateNormal]; // Change button title to "Hide"
	}
}

Make sure to deallocate the imageView in the dealloc method.

- (void)dealloc {
	[imageView release];
 
	[super dealloc];
}

Snippet to try:

Let’s say you have a view overlaying another view that you would like to close in a fancy fashion when the user click a button thus displaying the view directly below it. Put this code as your button’s IBAction message handler and tell me that doesn’t spice up your app like crazy!

-(IBAction)onButtonClick:(id)sender {
	[UIView transitionWithView:self.view duration:0.2 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
		self.view.frame = CGRectOffset(self.view.frame, 0, -self.view.frame.size.height);
	} completion:^(BOOL finished) {
		[self.view removeFromSuperview];
		[self release];
	}];
}

That’s all there is to it. Quite simple really and if your project already moves an item into view, you can make it animate by adding two lines of code. Feedback is much appreciated! Enjoy!

Download:
View Animation Demo Source Code – 475k

Random Posts:

If you found this useful, shoot me a small donation or at the very least leave a comment, every bit of encouragement helps keep me motivated to update with more content on a regular basis!

Comments

12 Responses to “Simple iPhone Animation Tutorial”

  1. Simon Singh says:

    Cool thanks!

  2. Nick Vellios says:

    Simon, glad you liked it! Thanks for reading.

  3. [...] This post was mentioned on Twitter by Burns Media, Nick Vellios. Nick Vellios said: Tutorial and example source code showing how to create simple animations on the iPhone: http://bit.ly/cq0U4Z [...]

  4. Revo says:

    Forwarded this to my friend starting iPhone development. Your site is such a great resource!

  5. Where is the rss feed?

  6. Blingkid Shorts 1 – Special Edition | Movie City Online says:

    [...] Simple iPhone Animation Tutorial « iPhone Open Source – Nick Vellios [...]

  7. WP Theme says:

    Nice dispatch and this mail helped me alot in my college assignement. Thanks you on your information.

  8. rob says:

    I’m currently moving from as3 to objective-c environment and I find your tutorials very helpful, thanks a lot fore sharing

  9. Jerome Reavely says:

    It’s the first time I have heard that in Macedonia, obits are an unusual observe.

Twitter Me