Multiple UIBarButtonItems in UINavigationBar

Ever wondered how to place more than one button into a navigation bar in your app? I know it doesn’t look neat at all! The class UIBarButtonItem allows us to initialize a new instance with a custom view. This instance can be used as a kind of a toolbar and you can put as much buttons as you like in there. The toolbar again can be used for the rigthtBarButtonItem or leftBarButtonItem. Please remember:

  • Keep your interface clean and simple and
  • Be consistent with the iPhone Human Interface Guideline

For those guys, who still demand on more than one button on the left or right side of a navigation bar, the following code snippet could be useful.

// create a toolbar where we can place some buttons
UIToolbar* toolbar = [[UIToolbar alloc]
                        initWithFrame:CGRectMake(0, 0, 100, 45)];
[toolbar setBarStyle: UIBarStyleBlackOpaque];
 
// create an array for the buttons
NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];
 
// create a standard save button
UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]
	initWithBarButtonSystemItem:UIBarButtonSystemItemSave
	target:self
	action:@selector(saveAction:)];
saveButton.style = UIBarButtonItemStyleBordered;
[buttons addObject:saveButton];
[saveButton release];
 
// create a spacer between the buttons
UIBarButtonItem *spacer = [[UIBarButtonItem alloc]
	initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
	target:nil
	action:nil];
[buttons addObject:spacer];
[spacer release];
 
// create a standard delete button with the trash icon
UIBarButtonItem *deleteButton = [[UIBarButtonItem alloc]
	initWithBarButtonSystemItem:UIBarButtonSystemItemTrash
	target:self
	action:@selector(deleteAction:)];
deleteButton.style = UIBarButtonItemStyleBordered;
[buttons addObject:deleteButton];
[deleteButton release];
 
// put the buttons in the toolbar and release them
[toolbar setItems:buttons animated:NO];
[buttons release];
 
// place the toolbar into the navigation bar
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
                                          initWithCustomView:toolbar];
[toolbar release];

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

4 Responses to “Multiple UIBarButtonItems in UINavigationBar”


Leave a Reply