How to add Navigation Bar "Plus" button, and use it in code

1.9k views Asked by At

I have a table view in a Navigation Controller, with a Navigation Bar at the top. I would like to add a plus button on the right of this navigation bar, and for the button to post an NSLog when pressed. However, all online resources suggesting to add the navigation bar programatically have failed. How can I do this?

All help appreciated.

Edit: Here is some code I used in my viewDidLoad method. So that you know, I simply added this code, and did nothing else:

UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleDone target:self action:@selector(doSave:)];
self.navigationItem.rightBarButtonItem = anotherButton;
[anotherButton release];  

Edit 2: When I created the project, in the Interface Builder, I created a Navigation Controller, moved the arrow which was to the left of my FirstViewController to the Navigation Controller, then deleted my FirstViewController. Would this have stopped the code from working?

2

There are 2 answers

6
stromdotcom On

In your ViewController's viewDidLoad:

UIBarButtonItem *plusButton = [[UIBarButtonItem alloc]initWithTitle:@"+" style:UIBarButtonItemStylePlain target:self action:@selector(plusButtonHit)];
self.navigationItem.rightBarButtonItem = plusButton;

-(void)plusButtonHit {
   // do something
   NSLog(@"Log something");
}

If you want to use an image, just create your bar button with an image instead of text.

0
Vyacheslav Zubenko On
- (void)viewDidLoad {
    [super viewDidLoad];
     
    UIBarButtonItem *plusButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(plusButtonHit)];
    self.navigationItem.rightBarButtonItem = plusButton;
}

- (void)plusButtonHit {
    NSLog(@"Log something");
}