Servin Mobile Software


How to use iPhone Timers and Animated Views: A Tutorial for Professional Software Developers


Norman McEntire

Version 1.3 July 28. Thank you Mike M.

Version 1.2 May 23. Thank you Seth R.

Version 1.1 Mar 1

Version 1.0 January 17

Copyright © 2009 Servin Corporation. http://servin.com


Introduction

In this Servin Mini-Course, you will learn how to create an iPhone View-Based Application that changes the view based on a timer, and each individual view will use automation during the transition.


iPhone Software Skills You Will Learn


Prerequisites


Startup Xcode

If Xcode is not already running, start it up:

  1. On the Mac Desktop, double-click on the Finder icon (the icon with the face on it).
  2. On the left-side of the Finder window, click on Macintosh HD.
  3. On the right-side of the Finder window, click on the Developer folder.
  4. Click on the Applications folder.
  5. Double-click on the Xcode icon.

At this point, you should see the Xcode menu at the top of your desktop.


Create New Xcode Project

With Xcode running, create a new Xcode project:

  1. File > New Project.
  2. On the left-side of the New Project window, select Application under iPhone OS.
  3. On the right-side of the New Project window, select View-Based Application.
  4. Click on the Choose button.
  5. Enter TimersAndAnimation for the project name.
  6. Click on Save button.

At this point, you should see Xcode open a new window that shows a number of files.


Build Default App

Go ahead and build the default application:

  1. Click on the Build and Go button.
  2. After a brief moment, you should see the code running in the iPhone Simulator.
  3. Observe the status bar at the top of the window, and a gray window everywhere else.
  4. In the iPhone Simulator, press the Home button to stop the application.

Add myCounterLabel to TimersAndAnimationViewController Class

In this exercise, you will edit the TimersAndAnimationViewController class to add a member variable named myCounterLabel of type UILabel.

You will use the myCounterLabel member variable to keep a count of the timer ticks from the (soon to be added) timer.

  1. In Xcode, in the Groups & Files window on the left-side, click on the Classes folder.
  2. You should see the following files on the right-side of the window:
    TimersAndAnimationAppDelegate.h
    TimersAndAnimationAppDelegate.m
    TimersAndAnimationViewController.h
    TimersAndAnimationViewController.m
    
  3. Select TimersAndAnimationViewController.h so that it appears in the Xcode editor window.
  4. Edit the code to match the following:
    #import <UIKit/UIKit.h>
    
    @interface TimersAndAnimationViewController : UIViewController {
    
    	IBOutlet UILabel *myCounterLabel;
    
    }
    
    @property (nonatomic, retain) UILabel *myCounterLabel;
    
    @end
    
  5. The IBOutlet syntax means that this member variable will be connected by Interface Builder to a visible UILabel control. Think of this as the "outlet" that allows this code to connect to a UILabel that was created in Interface Builder.
  6. The @property syntax means that this member variable will be accessed using the property notation, i.e., object.property. This feature is new to Objective-C 2.0
  7. Now select TimersAndAnimationViewController.m into the Xcode editor.
  8. Edit the code to match the following:
    #import "TimersAndAnimationViewController.h"
    
    @implementation TimersAndAnimationViewController
    
    @synthesize myCounterLabel;
    
    - (void)viewDidLoad {
    	[super viewDidLoad];
    
    	self.myCounterLabel.text = @"0";
    
    }
    
  9. The @synthesize syntax tells the Objective-C 2.0 compiler to generate two methods: one named myCounterLabel, used for getting the current value, and another named setMyCounterLabel, used for setting the value.
  10. The viewDidLoad method is called after the view is created from the TimersAndAnimationViewController.xib.
  11. Click on Build and Go to confirm that you do not have any syntax errors. Although your code should build and run, it will look the same as before, i.e., you will not yet see the myViewCounter value on the view.
  12. Press Home in iPhone Simulator to stop the application.

As a review, in this exercise you created and initialized a member variable named myCounterLabel. In the next exercise, you will connect this member variable with an actual UILabel control.


Add UILabel to TimersAndAnimationViewController.xib

In this exercise, you will use Interface Builder to add a UILabel to the TimersAndAnimationViewController.xib file.

You will also connect the UILabel created in Interface Builder with the member variable myCounterLabel.

  1. In Xcode, in the Groups & Files window on the left, click on the Resources folder to view a list of resource files.
  2. You should see these three files:
    Info.plist
    MainWindow.xib
    TimersAndAnimationViewController.xib
    
  3. Double-click on the TimersAndAnimationViewController.xib file.
  4. After a brief moment, you will see the Interface Builder application start up, displaying a gray window titled "View", along with other windows.
  5. Select Tools > Library.
  6. Expand the Library:
    - Library
    	- Cocoa Touch Plugin
    		- Controllers
    		- Data Views
    		- Inputs and Values
    		- Windows, Views, and Bars
    
  7. Select Inputs and Values.
  8. Drag Label onto the gray View window.
  9. You can keep the default text of "Label".
  10. Select the window titled TimersAndAnimationViewController.xib.
  11. Control-Click on Files' Owner to view the list of outlets:
    - Outlets
    	- myCounterLabel
    	- navigationItem
    	- tabBarItem
    	- view
    
  12. Control-click-drag from the "O" that is at the end of myCounterLabel to the "Label" text that is on the gray window. This is a key step, for it connects the Outlet named myCounterLabel to the UILabel on the view.
  13. File > Save.
  14. Command+Tab to return Xcode.
  15. Build and Go.
  16. Observe that the "0" now shows. As you know, this means that method viewDidLoad was called, and the self.myCounterLabel.text was set to @"0".
  17. Press Home in iPhone Simulator to end the application.

As a review, in this exercise you used Interface Builder to connect UILabel on the view to the myCounterLabel Outlet.


NSTimer

In this exercise, you will use the NSTimer class to call a method in the TimersAndAnimationViewController to update the count every 2 seconds.

  1. In Xcode select TimersAndAnimationViewController.m.
  2. Create a timer by enhancing viewDidLoad:
    - (void)viewDidLoad {
    	[super viewDidLoad];
    	self.myCounterLabel.text = @"0";
    
    	[NSTimer scheduledTimerWithTimeInterval:2.0f
             	 target:self
    	 	 selector:@selector(updateCounter:)
    	 	 userInfo:nil
    	 	 repeats:YES];
    
    }
    
  3. The NSTimer class provides several class methods for setting up timers. The one used above sets an interval, the object to call (self in this case), what method to call (updateCounter: in this case), any user-specific info (nil here), and whether to repeat the call every interval (YES in our case).
  4. Enter the following code before the viewDidLoad method:
    
    - (void)updateCounter:(NSTimer *)theTimer {
    	static int count = 0;
    	count += 2;
    	NSString *s = [[NSString alloc]
    		        initWithFormat:@"%d", count];
    	self.myCounterLabel.text = s;
    	[s release];
    }
    
    
  5. Build and Go.
  6. Your application should run as before, except now you should see the number incrementing by two every 2 seconds.
  7. Press Home in the iPhone Simulator to end the app.
As a review, in this exercise you added NSTimer to call a method on a periodic interval to update the count.


Add Subviews To TimersAndAminationViewController.xib

In this exercise, you will use Interface Builder to add three subviews to the gray View window, one red, one green, one blue.

  1. In Interface Builder, select the TimersAndAnimationViewController.xib window.
  2. Double-click on View, which selects the gray View window.
  3. Tools > Library to display the Library window.
  4. Example Library as follows:
    - Library
    	- Cocoa Touch Plugin
    		- Controllers
    		- Data Views
    		- Inputs Values
    		- Windows, Views and Bars
    
  5. Select Windows, Views and Bars.
  6. Drag a View from the Library onto the gray View; this makes it a subview of the gray View window.
  7. Re-size the subview to be a small square, about large enough enough to hold the word "color".
  8. Draw two other Views in the same manner; drag them from the Library, drop onto the gray View window, then re-size so they are no larger than needed to hold the text "color".
  9. Select the first subview that you positioned on the gray view.
  10. Tools > Attributes Inspector.
  11. Change the background color to red.
  12. Repeat for the other two subviews, setting one background color to green, and the other to blue.
  13. File > Save.
  14. Command+Tab to return to Xcode.
  15. Build and Go.
  16. As before, you should see the counter incrementing every second. You should also see the three colored subviews displayed, one red, one green, one blue.

As a review, in this exercise you added three subviews to TimersAndAnimationViewController.xib.


Connecting Subviews to Code

In this exercise, you will add member variables for each of the subviews, using IBOutlet for each. Later you will use Interface Builder to connect the member variables to the subviews.

  1. In Xcode, click on the Classes folder.
  2. Select TimersAndAnimationViewController.h into the Xcode editor.
  3. Edit to code to match the following:
    #import <UIKit/UIKit.h>
    
    @interface TimersAndAnimationViewController : UIViewController {
    	IBOutlet UILabel *myCounterLabel;
    
    	IBOutlet UIView *redView;
    	IBOutlet UIView *greenView;
    	IBOutlet UIView *blueView;
    
    }
    @property (nonatomic, retain) UILabel *myCounterLabel;
    
    @property (nonatomic, retain) UIView *redView;
    @property (nonatomic, retain) UIView *greenView;
    @property (nonatomic, retain) UIView *blueView;
    
    @end
    
  4. As before, this code adds member variables to the class, and also makes the member variables accessible to Interface Builder.
  5. In addition, as before, the @property ensures that the member variables can be accessed as properties, using the name.property syntax.
  6. Select TimersAndAminationViewController.m into the Xcode editor.
  7. Edit the code to match the following:
    #import "TimersAndAnimationViewController.h"
    
    @implementation TimersAndAnimationViewController
    
    @synthesize myCounterLabel;
    
    @synthesize redView;
    @synthesize greenView;
    @synthesize blueView;
    
    ...
    
    
  8. Continue to edit the code:
    - (void)updateCounter:(NSTimer *)theTimer {
    
    	static int count = 0;
    	count++;
    
    	NSString *s = [[NSString alloc]
    		       initWithFormat:@"%d", count);
    	self.myCounterLabel.text = s;
    	[s release];
    
    	self.redView.hidden = YES;
    	self.greenView.hidden = YES;
    	self.blueView.hidden = YES;
    
    	switch (count & 0x03) {
    		case 0: self.redView.hidden = NO; break;
    		case 2: self.greenView.hidden = NO; break;
    		case 4: self.blueView.hidden = NO; break;
    	}
    
    }
    
  9. Select Build and Go to build and run your app. There will be no visible changes as the app runs. We first need to use Interface Builder to connect the UIViews in our code to the UIView controls in the TimersAndAnimationViewController.xib file

As a review, in this exercise you added code to handle the three subviews, turning each view off until it is time for it to display.


Using Interface Builder to Connect Subviews

In this exercise, you will use Interface Builder to connect the member variables to the view.

  1. Press Command+Tab to select Interface Builder.
  2. Select the TimersAndAnimationViewController.xib window.
  3. Select File's Owner.
  4. Control+Click to display the list of Outlets:
    - File's Owner Outlets
    	- blueView
    	- greenView
    	- myCounterLabel
    	- navigationItem
    	- redView
    	- tabBarItem
    	- view
    
  5. For each of the three outlets (redView, greenView and blueView), Control-Click-Drag from the Outlet to the appropriate colored subview on the gray window.
  6. To repeat: from the "O" at the end of each appropriate outlet (redView, greenView, blueView), control-click-drag from the "O" to the colored subview.
  7. File > Save.
  8. Command+Tab to return to Xcode, then Build and Go.
  9. You should see the counter counting. You should also see the colored subviews going from hidden=YES to hidden=NO, based on the value of the count.
  10. Press Home in the iPhone Simulator to exit the app.

As a review, in this exercise you used Interface Builder and control-click-drag to connect the outlets to the controls.


Animation of Views

In this exercise, you will enable animation of the three colored views.

  1. In Xcode, select the TimersAndAnimationVieweControllers.m into the Xcode editor.
  2. Edit the updateCounter: method to match the following:
    - (void)updateCounter:(NSTimer *)theTimer {
    
    	static int count = 0;
    	count++;
    
    	NSString *s = [[NSString alloc]
    		       initWithFormat:@"%d", count);
    	self.myCounterLabel.text = s;
    	[s release];
    
    
    	CGContextRef context = UIGraphicsGetCurrentContext();
    
    	[UIView beginAnimations:nil context:context];
    	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    	[UIView setAnimationDuration:1.0f];
    
    	[self.redView setAlpha:(float)((count & 0x07) == 0)];
    	[self.greenView setAlpha:(float)((count & 0x07) == 2)];
    	[self.blueView setAlpha:(float)((count & 0x07) == 4)];
    
    	[UIView commitAnimations];
    
    }
    
  3. Build and Go.
  4. Observe that the three colored views now fade in/out.

As a review, in this exercise you used animation to fade the three views in/out.


Skills Review


How To Contact Author

Feel free to contact the author for any of the following:


Updated 2009 July 28
Content viewable on all web browsers, including smart mobile phone devices.
Copyright © 1995-2009 Servin Corporation. All rights reserved.