Customizing UINavigationController Toolbar Elements

On iPhone OS 3.0, you can set UINavigationController toolbar items using the setToolbarItems:animated: method. However, this requires passing an array of UIToolbarItems elements. Although I could programmatically create these toolbar elements, I would rather create them in Interface Builder, if possible.

With this in mind, I created the UIToolbar in "MyGreatViewController.xib" and populated it with the necessary toolbar elements. Then in "MyGreatViewController.m" I get the elements from the toolbar and pass them to setToolbarItems:animated: ::

 - (void)viewDidLoad { [super viewDidLoad]; [self setToolbarItems: [toolbar items]]; } 

... where toolbar is an IBOutlet related to UIToolbar.

Is this a good approach? Is there a better way to do this? Should I just create items programmatically?

+7
cocoa-touch interface-builder uinavigationcontroller uitoolbar uitoolbaritem
source share
2 answers

This is a perfectly acceptable way to do this, but keep in mind that downloading xib files is quite expensive on iPhone, and it might be faster to create toolbar items programmatically in your viewDidLoad method.

+4
source share

I don’t know if this is registered anywhere, but I found that in the Builder interface, if you include the navigation controller toolbar, you can drag and drop the bar elements into your view controller and they will be automatically displayed in the navigation controller's control panel.

For example, here we can do (using Xcode 3.2 on Snow Leopard):

  • File-> New Project .... Select the Navigation Application and create a project.
  • Open MainWindow.xib in the interface builder.
  • Select a navigation controller, and in the attribute inspector, select the "Show toolbar" checkbox. This will cause the toolbar object to appear.
  • Drag a toolbar item from the library to the toolbar. It will appear on the toolbar. If you check the hierarchy in the NIB, you will see that this new item is a child of the RootViewController .

It seems that all the bar button elements added as children of the navigation bar will appear on the navigation bar, and any button bar elements added as children of the view controller will be displayed on the toolbar.

(I accidentally stumbled upon this. If anyone can find documentation for this behavior or any additional information, I would love to hear about it.)

+12
source share

All Articles