Among other things, I’m writing an app using Xcode 4.2.1 targeting iOS 4.3. I’d like to focus on the app functionality and create a UI that behaves normally. My expectation is that tools will promote and make easy doing normal things. For example, it is exceedingly normal to use a Navigation controller and and have some views in the hierarchy show a toolbar. However, I could not figure out how I’m supposed to express this idea in Interface Builder.

Various example applications demonstrate adding toolbar buttons to the root view, which indeed works beautifully. The sample projects show a NIB object hierarchy that includes the Navigation Controller object. Within this NIB, UIBarButtonItems added under view controllers get added correctly to the toolbarItems array and they show up nicely.

But how do you define toolbar items in a NIB you have created for a subview? IB does not offer seamless support, so the solution doesn’t show up in anyone’s sample. If there is a correct way to do this in IB, I haven’t found it. In lieu of direct support, here’s my way to define a toolbar for a sub-view. It’s visual and requires only three lines of code.

  1. In MyViewController.h:
  @property (nonatomic, retain) IBOutlet UIToolbar *toolbarPrototype; 
  1. In MyViewController.m:
  @synthesize toolbarPrototype = _toolbarPrototype;
  1. In MyViewController.m method viewDidLoad:
  self.toolbarItems = self.toolbarPrototype.items;
  1. Create a toolbar in the nib and add items as desired. It’s a separate top level item in the NIB, not a child of the view.

  2. Connect the File’s Owner toolbarPrototype outlet to the toolbar item defined above

That’s it! If you’re not seeing it, make sure to set a breakpoint in viewDidLoad and poke around at the values you see.

FWIW, another way to do it that reduces the line count to 2 but increases the chance of wire up error is

  1. In MyViewController.h:
@property (retain) IBOutletCollection(UIBarButtonItem) NSArray *toolbarItems;
  1. In MyViewController.m:
// Relies on setToolbarItems: defined for UIViewController base class
  @dynamic toolbarItems;
  1. Create the toolbar as above, or just create a set of UIBarButtonItems as top level NIB items.

  2. Connect all the UIBarButtonItems, IN ORDER, to the File’s Owner toolbarItems outlet collection.

Is there a better way? Please let me know.