How to create a UIBarButtonItem in code and make it call a method

Some things are really easy to do via a Storyboard – but when you want to create the same thing in code I frequently forget how to do it.

Turns out it’s equally simple: this example assumes you have a View Controller which is embedded in a Navigation Controller (so it already has a UINavigationBar at the top). Here’s how you add a button to it, set the title and target, and tell it what to do when it’s pressed:

- (void) viewDidLoad
    [super viewDidLoad];
    // first we create a button and set it's properties
    UIBarButtonItem *myButton = [[UIBarButtonItem alloc]init];
    myButton.action = @selector(doTheThing);
    myButton.title = @"Hello"; = self;
    // then we add the button to the navigation bar
    self.navigationItem.rightBarButtonItem = myButton;

// method called via selector
- (void) doTheThing {
    NSLog(@"Doing the thing");

You can set the button on the left hand site by using self.navigationItem.leftBarButtonItem

Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at and