Adding Multiple Bar Button

Sometimes you want to add more than one barButtonItem to the navigation bar of your application on either the left or the right side.  Unfortunately, this cannot be done by dragging the buttons in Xcode and dropping them on the navigation bar.  This must be done in code.

Start a new “single view” application in Xcode.  Open Main.storyboard, select view controller and then embed it in a Navigation Controller.  This is done by clicking on (Editor->Embed In->Navigation Controller)

We will add the buttons in ViewController.m inside the viewDidLoad method.  Declare and initialize two UIBarButtonItems.  One of them will be an edit button and the other one will be a save button.  The target will be self and the action will be methods that you will need to implement to do whatever you need them to do when the buttons are clicked.

UIBarButtonItem *editBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editAction)];

UIBarButtonItem *saveBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(saveAction)];

Finally, we need to add the buttons to the navigation bar.

self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:editBarButtonItem, saveBarButtonItem, nil];

This is what your viewDidLoad should look like at this point.


- (void)viewDidLoad
{
    [super viewDidLoad];

    UIBarButtonItem *editBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editAction:)];

    UIBarButtonItem *saveBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(saveAction:)];

    self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:editBarButtonItem, saveBarButtonItem, nil];   
}

We also need to implement the methods editAction and saveAction.


-(void)editAction
{
    NSLog(@"edit button clicked");
}

-(void)saveAction
{
    NSLog(@"save button clicked");
}

At this point you can run the app and see that the two buttons are added to the navigation bar. Clicking on them prints the log messages to the console.