How to create multiple buttons in a UINavigationBar

Screen Shot 2014-05-17 at 09.54.04Sometimes a single button left and right is just not enough for complex apps. Especially on the iPad we have this large space in the navigation bar. But Interface Builder only allows us to add one button on the left and one on the right.

How do we add more buttons to those spaces? Code is the answer.

Both the left and the right space of a UINavigationBar can take an array of barButtonItems which we can populate with as many buttons as space will allow.

In this example I’m using the Master/Detail template to create an array in the viewDidLoad method of the DetailViewController. This will create the effect shown in the screenshot:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configureView];
    // create three funky nav bar buttons
    UIBarButtonItem *one = [[UIBarButtonItem alloc]initWithTitle:@"One" style:UIBarButtonItemStylePlain target:self action:@selector(testMethod)];
    UIBarButtonItem *two = [[UIBarButtonItem alloc]initWithTitle:@"Two" style:UIBarButtonItemStylePlain target:self action:@selector(testMethod)];
    UIBarButtonItem *three = [[UIBarButtonItem alloc]initWithTitle:@"Three" style:UIBarButtonItemStylePlain target:self action:@selector(testMethod)];
    // create a spacer
    UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    space.width = 30;
    NSArray *buttons = @[one, space, two, space, three];
    self.navigationItem.rightBarButtonItems = buttons;

Note how you can create fixed spaces between the buttons as shown.

You can also space those buttons evenly across the whole bar by using the UIBarButtonSystemItemFlexibleSpace, in which case there’s no need to pass the width parameter. When you do, the buttons will be spaced between the right side of the bar and the title if there is one, or across the whole bar if the title is empty.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.