• USA : +1 973 910 5725
  • INDIA: +91 905 291 3388
  • info@tekslate.com
  • Login

UIView and UIViewController

Handling Application Life Cycle Events

UIApplication forwards several important events to its UIApplicationDelegate to handle. For instance, applicationSignificantTimeChange: handles a significant time change while your application is running. The method didChangeStatusBarOrientation: handles the event fired when the status bar’s orientation is changed from portrait to landscape or landscape to portrait. Table 6-1 lists UIApplicationDelegate’s application life cycle event-handling methods.

With the exception of applicationDidFinishLaunching:, the methods in Table 6-1 are not required, but you should implement most of them if you wish developing a robust application.

Two of the more important application life cycle events are your application’s startup and shutdown. The applicationDidFinishLaunching: method—a required method—is where you initialize your UIViewControllers, your UIWindow, add a UIView to the window, and then launch your application’s user interface. The method is also useful for restoring your application’s state, and is where you perform application initialization. The applicationWill Terminate: method is useful for saving your application’s state. You might also use this method to perform cleanup.



application:didChangeStatusBar Orientation:



application:willChangeStatusBar Orientation:duration:







-(void) application:(UIApplication *)

application didChangeStatusBarFrame:

(CGRect) oldStatusBarFrame

-(void) application: (UIApplication *)

application didChangeStatusBarOrie ntation:

(UIInterfaceOrientation) oldStatusBarOrientation

  • (BOOL) application: (UIApplication *)
  • application handleOpenURL: (NSURL *) url
  • (void) application: (UIApplication *)
  • application willChangeStatusBarFrame:
  • (CGRect) newStatusBarFrame

-(void) application: (UIApplication *)

application willChangeStatusBarOri

entation:(UIInterfaceOrientation) newStatusBarOrientation duration:



(NSTimeInterval) duration

-(void) applicationDidBecomeActive:

(UIApplication *) application

– (void) applicationDidFinishLaunching:

(UIApplication *) application


(UIApplication *) application

-(void) applicationSignificantTimeChange:

(UIApplication *) application

-(void) applicationWillResignActive:

(UIApplication *) application

-(void) applicationWillTerminate:

(UIApplication *) application

Xcode offers a feature called Code Sense. As you are typing, Xcode will suggest what it thinks you are typing. If correct, press the TAB key and Xcode finishes typing for you. You can ignore the suggestion by continuing to type. If you are not certain the suggestion is correct, press the ESC key and Xcode presents a drop-down list with possible completions (Figure 6-9). If you do not see this feature, ensure Xcode is configured correctly in Xcode Preferences (Figure 6-10).




Figure 6-9 Code completion in Xcode




 Application Interruptions

As your application functions, it is likely to receive interruptions. An incoming phone call causes your application to become inactive. If you decide answering the call, your application terminates. Other events that might cause your application to become inactive include calendar alerts and putting your device to sleep (locking your device). The application WillResignActive: method in UIApplicationDelegate executes just prior to your application becoming inactive. The applicationDidBecomeActive: method executes just after your application becomes active again. For instance, if you are running your application and lock the screen, your application’s delegate executes the applicationWillResignActive: method. When you later unlock the screen, your application’s delegate executes the applicationDid BecomeActive: method.Another important method is applicationDidReceiveMemoryWarning: method. The iPhone has limited memory—use too much and the operating system will terminate your application. But the operating system warns your application first. When UIApplication receives this event, it forwards the event to its delegate’s applicationDidReceiveMemoryWarning: method. The delegate can then handle the application’s response to the warning. For instance, it might release a shared data structure or take other memory reclaiming actions.


Although not required, your application should handle these important events in its UIApplicationDelegate. If it does not, Apple might reject your application when submitted for inclusion in the App Store.

Handling Application Interruptions

In this task, you explore the applicationDidReceiveMemoryWarning:, applicationWillResign Active:, and applicationDidBecomeActive: methods in UIApplicationDelegate.

  1. Add the methods application Did Receive MemoryWarning:,application DidBecomeActive:, andapplication WillResignActive: toAddViewProjectDelegate’s implementation (Add m).Add a single NSLog statement to each method. The methods should appear similar to Listing 6-4.
  2. Click Build And Go, and execute the application in the iPhone
  3. Select Hardware | Simulate Memory Warning from the iPhone Simulator’s
  4. Select Hardware | Lock from the iPhone Simulator’s Unlock and then quit your application.
  5. Review the Debugger Console, which should appear similar to Listing 6-5.


Listing 6-4 AddViewProjectAppDelegate’s three additional methods

-(void)applicationDidReceiveMemoryWarning:(UIApplication *) application { NSLog(@”hey got a memory warning….”);


-(void)applicationWillResignActive:(UIApplication *) application { NSLog(@”hey I’m about to resign active status….”);


-(void)applicationDidBecomeActive:(UIApplication *) application { NSLog(@”hey I’m active….”);


Listing 6-5 Console output from running application

[Session started at 2008-12-07 14:56:49 -0500.]

2008-12-07 14:56:50.737 ProjectEight[2465:20b] fired application did finishLaunching…

2008-12-07 14:56:50.740 ProjectEight[2465:20b] added first view controller and made it visible…


2008-12-07 14:57:03.247 AddViewProject[2465:20b] hey I’m active….

2008-12-07 14:57:08.094 AddViewProject[2465:20b] about to terminate…


The application executed the applicationDidBecomeActive: method when you started it and then after you unlocked the Simulator. It called applicationDidReceiveMemoryWarning: when you selected the Simulate Memory Warning menu item. And when the application was about to become inactive after locking, the UIApplicationDelegate executed the application WillResignActive: method.


UIView and UIViewController

Key Skills & Concepts

  • Understanding the UIView and UIViewController
  • Creating a single view application using the View-based Application Template
  • Creating a single view application using the Window-based Application Template
  • Understanding an application delegate’s root view
  • Setting an application’s root view in Interface Builder
  • Setting an application’s root view using code
  • Understanding UIView life cycle methods

UIViews are how the iPhone displays information on the screen. The UIView class is responsible for displaying a rectangular area on the screen. The UIViewController manages the UIView and is responsible for handling the view’s logic. The UIViewController is the glue between the view—the UIView—and your data classes—the model.There are many UIView subclasses you might work with while developing an iPhone application. In fact, every graphical component you use on an iPhone graphical user interface (GUI) is a UIView subclass. Technically speaking, everything is a view. But typically, when documentation or some other material refers to a ―view,‖ it is referring to a content view.A content view is a view that has a view controller and is responsible for presenting a screen’s worth of user interface.

The UIView Class

The UIView’s responsibilities are drawing to the screen and handling events associated with a user’s interaction with an application. A UIView has an associated UIViewController. The UIViewController manages the view. The view controller loads and unloads its associated views, manages views, and handles application life cycle events for its views. Every graphical iPhone control you use in Interface Builder is a UIView subclass. Table 7-1 lists the UIView subclasses. Notice that UIScrollView and UIControl both have further subclasses listed in the table’s second column.

UIViews function as containers, controls, displays, alerts, action sheets, navigation controls, and as the application’s window. In future chapters, you consider most of these UIView types. This chapter limits itself to a simple display view and associated view controller.


The UIViewController Class

The UIViewController manages UIViews. It is responsible for creating, displaying, hiding, and destroying a view. The UIViewControl is also responsible for responding to a view’s life cycle events, handling orientation, and serving as a bridge between your application’s view and model. The view controller is your application’s controller in the model-view-controller design pattern.

View-based Application Template

The easiest route to creating a single view application is using Xcode’s View-based Application template. This template creates a single view and view controller for managing the view. While the view-based application is not as useful as Xcode’s other project templates, it is useful here, as it generates the most simple iPhone graphical application and provides a simple UIView and UIViewController example. In the next task, you generate an application using this template. But, before continuing, first review IBOutlets and IBActions.

IBOutlet and IBAction

You have already used IBOutlets and IBActions in previous chapters. Without really knowing what they are, you probably already have a good idea of what they accomplish; outlets and actions are how you connect things in a nib with things outside a nib. An outlet connects an instance variable outside a nib to an object in a nib.IBOutlet is a preprocessor directive, evaluates to void, and is ignored by the compiler,but all you really need to know is that IBOutlet is how Interface Builder knows the variable was created for its use. When adding a class, Interface Builder scans the class for IBOutlets and knows those variables are intended as outlets. You can then easily connect your graphical component to the variable, as Interface Builder adds the outlets to the inspector automatically for you to select. Note, though, Interface Builder doesn’t connect the outlets to anything; it just adds them. You are responsible for adding any connections.Actions are messages sent from objects in the nib to methods outside the nib. You define an action in your code using the IBAction keyword. Like IBOutlet, it’s a preprocessor directive and evaluates to void. You define an action in your code using the IBAction keyword. Also, like IBOutlet, when you add a class to Interface Builder, it scans the class for IBActions and adds them to the inspector for you to select. You can then connect user interface events to a specific method in your code. Note that a method designated as an action must not return a value, as the preprocessor replaces IBAction with void, and so all the compiler sees is void.An action also takes a single parameter, sender. The sender is the id of the control calling the action. So if a UIButton instance called changeLabelValue, the sender would be the pointer to the UIButton.

– (IBAction) changeLabelValue: (id) sender;

IBOutlet and IBAction don’t require much explanation, as you use these two directives so frequently they become second nature. Any instance variable external to Interface Builder that must communicate with a control in Interface Builder must be an IBOutlet. Any method that must be called from a control in Interface Builder must be an IBAction.

Using a View-based Application Template

  1. Create a new View-based Application using the Name the project SimpleView.
  2. Expand classes and notice Interface Builder created the SimpleViewViewController class for Expand Resources and notice the template generated a separate nib, SimpleViewViewController.xib, for the SimpleViewViewController.
  3. Open h and add a label and method for changing the label’s value. Make the label an IBOutlet and the method an IBAction (Listing 7-1).
  4. Open m and add the IBOutlet and IBAction definitions (Listing 7-2).
  5. Open xib in Interface Builder and change the view’s color. Add a UILabel and a UIButton to the UIView.
  6. Notice that SimpleViewViewController is the File’s Connect SimpleViewView Controller’s theLabel outlet to the label.
  7. Connect SimpleViewViewController’s changeTheLabel action to the Select Touch Up Inside.


Listing 7-1 SimpleViewViewController.h

#import <UIKit/UIKit.h>

@interface SimpleViewViewController : UIViewController { IBOutlet UILabel * theLabel;


@property (nonatomic, retain) UILabel * theLabel;

– (IBAction) changeLabelValue: (id) sender;


Listing 7-2 SimpleViewViewController.m

#import “SimpleViewViewController.h”

@implementation SimpleViewViewController

@synthesize theLabel;

– (IBAction) changeLabelValue : (id) sender { [theLabel setText:@”Hello World.”];

UIButton *theBut = sender; NSLog(theBut.currentTitle);

theBut.enabled = NO;

[theBut setTitle:@”Pressed Already” forState: UIControlStateDisabled];


– (void)dealloc { [theLabel release]; [super dealloc];



Take a moment to examine what the View-based Application template did for you. It created the SimpleViewViewController.xib and it also created a UIViewController subclass, SimpleView ViewController, by creating the SimpleViewViewController.h and SimpleViewViewController.m files. Moreover, it added the controller to the delegate (Listing 7-3).sIn the delegate, the template created the application’s window and view controller as outlets (Listings 7-3 and 7-4). In the delegate’s applicationDidFinishLaunching: method, the template added the view controller’s view to the window and then displayed the window. Notice that nowhere does the code allocate or initialize its window or view controller. Instead, the Info.plist specifies that MainWindow.xib is the application’s main nib, so it knows to load the MainWindow.xib and the nib handles window and view controller initialization.In the MainWindow nib, the template set the nib’s file’s owner to UIApplication. The template set SimpleViewAppDelegate as the application’s delegate and set the delegate’s window to the window in MainWindow.xib.The template also added a view controller to MainWindow.xib and set it as the delegate’s root view controller. Every delegate must have a root view controller. The root view controller in MainWindow.xib comes from the SimpleViewViewController.xib, also created by the template.The template created the UIView in its own xib, SimpleViewViewController.xib. It set SimpleViewViewController.xib’s file’s owner to SimpleViewViewController. It also set the controller’s view to the view in the xib.

Listing 7-3 SimpleViewAppDelegate.h

#import <UIKit/UIKit.h>

@class SimpleViewViewController;

@interface SimpleViewAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window;

SimpleViewViewController *viewController;



@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet SimpleViewViewController



Listing 7-4 SimpleViewAppDelegate.m

#import “SimpleViewAppDelegate.h”

#import “SimpleViewViewController.h”

@implementation SimpleViewAppDelegate

@synthesize window;

@synthesize viewController;

  • (void)applicationDidFinishLaunching:(UIApplication *)application { [window addSubview:viewController.view];

[window makeKeyAndVisible];


  • (void)dealloc { [viewController release];
  • [window release];

[super dealloc];

} @end

Using a Window-based Application Template

The View-based Application template hides many development details. If new to iPhone programming, chances are the View-based Application template does not help clarify a UIView, UIViewController, and their relationship. To help make their relationship clearer, you should understand what the View-based Application template accomplishes automatically.

Unlike a View-based Application template, a Window-based Application template requires understanding UIViews and UIViewControllers. When using the Window-based Application template, you must manually create a view and view controller and wire them together. In

this project, you create a single view application starting with a Window-based Application template. Creating a Window-based Application should solidify your understanding of the steps behind its creation.

  1. Create a new Window-based Application and name it
  2. Highlight Resources and create an empty Name the xib FirstViewController.xib.
  3. Highlight Classes and add a UIViewController named Xcode should have created FirstViewController.h and FirstViewController.m. Be certain the checkbox to create a xib is not checked.
  4. Open h and    import the FirstViewController. Add a UIViewController property to SimpleWindowAppDelegate.h so it appears the same as
  5. Modify m so it appears like Listing 7-6. Notice you must synthesize rootViewController and add its view to the window as a subview in the delegate’s applicationDidFinishLaunching: method.
  6. Build the This step is important, if you do not build or save the changes, any added actions or outlets will not appear in Interface Builder.
  7. Open xib  in  Interface  Builder.  Open  the document  window and notice that the File’s Owner isn’t set. Also notice there is no UIView.
  8. Drag a view from the library to the document window. Change the view’s
  9. Select File’s Owner and change its class to FirstViewController in the Object Identity Inspector
  10. Click the Connections Inspector and connect the view outlet to the view you added to the document
  11. Save and close the FirstViewController’s document Open MainWindow.xib in Interface Builder.
  12. Notice that there is no UIViewController or view set in the document window.
  13. Drag a view controller from the library to the document window (Figure 7-1).



                                                                            Figure 7-1 Adding FirstViewController to Mainwindow.xib


UIView and UIViewController



Figure 7-2 Setting Mainwindow.xib’s root view controller


  1. In the view controller’s inspector, change its NIB Name to FirstViewController and its type to
  2. Select Simple Window App Delegate in the document In its connections inspector, notice the rootViewController outlet. Connect this to the view controller just added (Figure 7-2).
  3. Save and quit Interface
  4. Click Build And Go to run the The view in FirstViewController.xib is loaded into the window and displayed.

Listing 7-5 SimpleWindowAppDelegate.h

#import <UIKit/UIKit.h>

@class FirstViewController;

@interface SimpleWindowAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window;

FirstViewController *rootViewController;


@property (nonatomic, retain) IBOutlet FirstViewController


@property (nonatomic, retain) IBOutlet UIWindow *window;


Listing 7-6 SimpleWindowAppDelegate.m

#import “SimpleWindowAppDelegate.h”

#import “FirstViewController.h”

@implementation SimpleWindowAppDelegate

@synthesize window;

@synthesize rootViewController;

  • (void)applicationDidFinishLaunching:(UIApplication *)application { [window addSubview:rootViewController.view];

[window makeKeyAndVisible];


  • (void)dealloc { [window release];

[rootViewController release];

[super dealloc];

} @end

In step 15, you connected the FirstViewController to the application’s delegate. This was an important step; it allowed the nib to set the delegate’s root view controller for you. The root view controller is the UIViewController that is first loaded by an application delegate. Remember, the application knew to load MainWindow.xib because it was in the application’s Info.plist. The application loaded MainWindow.xib, saw the FirstViewController object that was added to the document window and saw that the delegate’s root view controller was set to FirstViewController. The application also knew the controller came from FirstViewController .xib. Because of the object, variable, and nib setting, the application new to allocate and initialize a FirstViewController instance from FirstViewController.xib when loading MainWindow.xib. Because these relationships were established in Interface Builder, no manual code was necessary. This is how the View-based Application template builds a simple application, which you just duplicated manually using the Window-based application template.


In this example, you manually created a xib and linked it to its associated view controller. Step 3 specifically instructed you to not check the checkbox that also created a xib; had you checked the checkbox, Xcode would have created a xib, and automatically made all the necessary connections for you.








Review Date
Reviewed Item
UIView and UIViewController

“At TekSlate, we are trying to create high quality tutorials and articles, if you think any information is incorrect or want to add anything to the article, please feel free to get in touch with us at info@tekslate.com, we will update the article in 24 hours.”

0 Responses on UIView and UIViewController"

Leave a Message

Your email address will not be published. Required fields are marked *

Site Disclaimer, Copyright © 2016 - All Rights Reserved.