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];
Perfect – Thanks for taking the time to post this!
The last UIBarButtonItem instance created is not being released.
Dirk
Really great, exactly what i was looking for. Than you so much
I think as long as you don't overdo it.. it doesn't.. look.. THAT bad. But honestly, sometimes you need a '+' button as well as an edit button in a sub-table and that blasted back button is taking up the left side of the toolbar.
Regardless, thank you for the great post.