iPhone Coding: Working with the Navigation Bar

The iPhone Navigation Bar offers a simple way to add button-based navigation to your iPhone applications. Defined in UIKit/UINavigationBar.h, this class allows you to add one or two buttons to the kind of blue iPhone-looking bar shown here. Use these buttons to move between program screens or to add direct functionality to your application.

Here is the code for a very simple application that makes use of the Navigation Bar by placing two buttons on the top of the screen. Tap the buttons to update the displayed text. The source for this application includes:

To use a navigation bar, you must allocate it and initialize it with a frame. The frame defines the boundaries the bar will occupy in your window. The standard frame for one- or two-button navigation bars is 320 pixels wide by 48 pixels high frame based at the top-left of the iPhone window.

nav = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 48.0f)];

The showButtonsWithLeftTitle: rightTitle: leftBack: method sets the number and kinds of buttons. Set leftBack: to YES or NO to specify whether the left button uses the back-pointing shape you see for many iPhone applications. Pass standard NSStrings to each title or use nil to omit the button from the display. e.g.

e.g. [nav showButtonsWithLeftTitle: @"Hello" rightTitle: @"Bye" leftBack: NO]; produces the two buttons shown here.

[nav showButtonsWithLeftTitle: @"Back" rightTitle: nil leftBack: YES]; shows a single back-styled Back button.

You can set the names on your buttons at any time as well as update their appearance. For example, you can jump between the two presentations examples I just listed above without penality.

Make sure to set the navigation bar's delegate to your main application to be able to receive the navigationBar: buttonClicked: message. The button number (0 or 1) tells you which item was tapped. In this sample, the text updates (goodbye or hello) based on the clicked button.

Recommended