UIBarButtonItem – Programmatically

There is a great tutorial on how to programmatically create and customized the UINavigationController (including UIBarButtonItem) here.

One issue I had was while Adding items to the right of your Navigation Bar. A bar button item is created like so:


UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithTitle@"My Button" style:UIBarButtonItemStyleBordered target:self action:@selector(doSomething)];
self.navigationItem.rightBarButtonItem = myButton;
[myButton release];

The doSomething above, is a method and it looks like this:


- (IBAction)doSomething:(id)sender
{
NSLog(@"%@", @"My Button was pressed");
}

You might expect this to work, however, when the button is pressed the program will crash with an unrecognized selector error. This is because the signature of the doSomething method has a colon on the end of it: doSomething:

Therefore, the code for creating the UIBarButtonItem should be:


UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithTitle@"My Button" style:UIBarButtonItemStyleBordered target:self action:@selector(doSomething:)];
self.navigationItem.rightBarButtonItem = myButton;
[myButton release];

Tags: , ,

One Response to “UIBarButtonItem – Programmatically”

  1. Mike Kubacki says:

    I struggled with this for a couple of days and the colon is what I was missing. This is the only site I’ve found to talk about this. Thank you so much!

Leave a Reply