Friday, April 29, 2011

UINavigationController

This design pattern presents a hierarchy of views, one leading into the other when something is tapped. The class used for implementing the is UINavigationController. The settings app is a well known example of an app that has its core functioning based on the navigation controller and table views.


When you add the navigation controllers view to the window it will automatically add a navigation bar. The first view of the view controller is known as the root view.

Let us make a simple app which utilizes navigation controllers to present multiple views one after the other. Fire up XCode and click on a windows based app under projects. It sets up an app delegate and a nib file.

Now in XCode create a new UIViewController sublass along with a nib from the new file menu. Name is rootViewController. It will generate a .h, .m and nib file.

Again create a new UIViewController subclass and name it nextViewController. This also will generate three files.

Now go to the .m file of the app delegate and import the first classes we declared. The statements would be like these

#import "rootViewController.h"


Inside the applicationDidFinishLaunching method in the implementation file of the app delegate declare intances of both these classes

rootViewController *firstView = [[rootViewController alloc] init];

Now we have to present this view as the first view in the navigation pattern. To do that we will create an instance of UINavigationController and add firstView as its rootViewController.

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:firstView];

Now we tell this app to add the navigation controller's view to the app window

[window addSubview:navController.view];

Now that we no longer need a reference to firstView, we release it to properly handle memory

[firstView release];

Go to the .h file of of the rootViewController, and add a method declaration buttonPressed
-(IBAction)buttonPressed:(id)sender

We have added the IBAction return type since we plan to hook this method to a button in Interface builder. This button will tell the navigation controller to present the next view in the hierarchy which is the nextViewController.

Go to the .m file of the rootViewController and implement the method we declared in the header file.
Also add the following line

#import "nextViewController.h"

The method will bring in the next view. The code will be like

-(IBAction)buttonPressed:(id)sender
{
nextViewController *nextV = [[nextViewController alloc] init];
[self.navigationController pushViewController:nextV;
}

Now you set up a button in Interface builder, hook it up to this method and you're done.

No comments: