Skip to content

December 16, 2011

1

iPhone navigation bar plus table view application howto

by noise

We’re going to create a simple application for the iPhone using a navigation bar and a table view. This application will be able to move between 2 screens using a navigation bar. The first view will use a table view, and the text on the second screen will change depending on the selection from the table.

iPhone navigation bar plus table view - Final look

iPhone navigation bar plus table view app final look

Creating the XCode project

First, go ahead and create a new project. Choose the Empty Application template, name your project SimpleNavbarApp and choose as Device Family “iPhone”. This template will generate just the app delegate files: AppDelegate.h and AppDelegate.m. We will add more files to the project later.

iPhone navigation bar plus table view - Create Project

Adding the first view controller to the project.

Next, we will add a View Controller class which will be responsible for the first view of the app – the table view. Along with the class, we will add a nib file to design the first view.
Add a new file using the template UIViewController, then on the next screen choose as Subclass of “UITableViewController”, and name the class “RootViewController”. Check “With XIB for user interface” checkbox, because you also want a nib file generated.

We’ve chosen UITableViewController as a subclass because the first view will be a table view.

iPhone navigation bar plus table view - Add View Controller

iPhone navigation bar plus table view - Add Table View Controller

The class RootViewController will be the root controller of our navigation bar.
The nib file has just a Table View object added. This will hold the values that we will be listing on the first page and will serve as selections when moving to the next page. It also has the File’s Owner Class set as RootViewController already in Identity Inspector, and the View object is linked to the File’s Owner view. If you generated the nib file separately you have to do these settings yourself.

Adding table view values

We will add the table items as a NSMutableArray. First add a property to the RootViewController.h header file:

@property (retain) NSMutableArray *tableItems;

Add the synthesize line in RootViewController.m:

@synthesize tableItems = _tableItems;

We will initialize the array in the method viewDidLoad, just under [super viewDidLoad] call:

_tableItems = [[NSMutableArray alloc] init];
_tableItems = [NSMutableArray arrayWithObjects:@"Value1", @"Value2",
              @"Value3", nil];
[_tableItems retain];

We can also set here a title for the navigation bar:

self.navigationItem.title = @"First page";

Make sure you release the memory allocated for the tableItems array (add this at the end of RootViewController.m before @end):

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

Next we will need to modify 2 functions which set the number of rows of the table view.
In method numberOfSectionsInTableView set return value to 1. We only have one section in this table.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

In method numberOfRowsInSection set as return the number of elements of table tableItems:

- (NSInteger)tableView:(UITableView *)tableView
    numberOfRowsInSection:(NSInteger)section
{
return [_tableItems count];
}

Now we can define each row value in the method cellForRowAtIndexPath. This method is called once for each value in our tableItems array with an incremented index, so we will set the table row text as the corresponding value from tableItems.

First we will verify if memory for cell is allocated or not, by adding the following code before return line:

    if (cell == nil) {
        cell = [[[UITableViewCell alloc]
 initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] 
 autorelease];
    }

Then add the following line:

cell.textLabel.text = [_tableItems objectAtIndex:indexPath.row];

Adding the navigation bar to the main application window

We will add the navigation bar programmatically to the main window. Add a property of type UINavigationController to the AppDelegate.h interface. This will be used to hold a reference to our navigation bar.

@property (nonatomic, retain) UINavigationController *navController;

In AppDelegate.m file import the RootViewController.h header file:

#import "RootViewController.h"

and then synthesize the navController property:

@synthesize navController = _navController;

Add the following code to application:didFinishLaunchingWithOptions:

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UIViewController *rootController = [[RootViewController alloc] init];
 
_navController = [[UINavigationController alloc]
initWithRootViewController:rootController];
 
[rootController release];
 
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen]
                  bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
 
[self.window addSubview:_navController.view];
 
[self.window makeKeyAndVisible];
return YES;
}

At this stage the iPhone application will look like this when you run it:

iPhone navigation bar plus table view - Stage 1

Creating the second view

We now need to create the second view and add the functionality so when you click on a table row in the table view, the application will take you to the second view which will display a message to indicate the row which was selected.

We will start by adding a new view controller with a nib file. Add a new file to the project. Choose a UIViewController subclass template. This time choose as Subclass of “UIViewController” and name it SecondViewController. Select the checkbox “With XIB for user interface”.
We will add a label using the interface builder on the new nib file so it looks like this:

iPhone navigation bar plus table view - Second view

Next we will add an outlet for this label because we want to be able to change it later when we load the view. In order to add the outlet, CRTL drag from the label to the SecondViewController.h like in the following image:

iPhone navigation bar plus table view - Label Outlet

Choose as connection type Outlet and set the name myLabel. The Type will be automatically set to UILabel.

iPhone navigation bar plus table view - MyLabel Outlet

Code the actual navigation bar functionality

It is time to add code to RootViewController in order to add the second view in the navigation controller stack when a table row is chosen. Modify the method didSelectRowAtIndexPath from RootViewController.m in the following way:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
// send selected value
[secondViewController setValue:[_tableItems objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:secondViewController animated:YES];
[secondViewController release];
 
}

In this method we define a second view controller of type SecondViewController. We will push this controller into the navigation controller stack, but before we will also send the table row selected value using a method setValue which we will define later in SecondViewController.

In SecondViewController.h we define the method setValue:

- (void) setValue:(NSString*)val;

and we also define a NSString variable which we will use to hold the value sent from the first view controller.

NSString *labelVal;

In SecondViewController.m we will release the temporary labelVal variable in dealloc method:

[labelVal release];

and of course, we will need to implement the method setValue. This method will keep the value received from the first view controller in labelVar. At this point we cannot set the label value directly to the label because the view is not initiated and the label is not yet created.

- (void) setValue:(NSString*)val {
 
labelVal = [NSString stringWithFormat:@"%@", val];
[labelVal retain];
 
}

When the view is loaded, in method viewDidLoad we can set the value for the label using the defined myLabel outlet:

_myLabel.text = [NSString stringWithFormat:@"%@", labelVal];

Mission accomplished, the iPhone app built using navigation bar and table view is ready!

We can run the app now, and it will look like in the following screen:

iPhone navigation bar plus table view - Final look

You can download the project here: iPhone navigation bar plus table view application.

Leave a Reply

required
required

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments