Add a navigation button

This will pickup where Create a view left off. So you can pick it up from there and download the source. You probably don’t even need the source but grab it if you wish

Now when you create a new view, in that view you might want to place a button in the navigation bar. This is pretty easy to do. So you want to open up the sub-view controller. In my example I called it BrowseViewController. So I will open up BrowseViewController.m and look for the loadView function. In my example you will see it commented ( /* */ ) out. For example.

/*
 Implement loadView if you want to create a view hierarchy programmatically
- (void)loadView {
}
 */

You will notice it is all green. To make it that function work just remove the /* and */ (don’t forget the comment text also) around it so now it looks like

- (void)loadView {

}

Now we want to add a button. So we just add in some code.

	UIBarButtonItem *addButton = [[[UIBarButtonItem alloc]
								   initWithTitle:NSLocalizedString(@"Something", @"")
								   style:UIBarButtonItemStyleBordered
								   target:self
								   action:@selector(doSomething)] autorelease];
	self.navigationItem.rightBarButtonItem = addButton;

So you see we are creating a button with text Something. We are also setting the style as a button with a border. the target is the object it will call on button press and the action is the function. We are auto releasing it also so we don’t have to do a [addButton release]; If we were to add that the application would seg fault.

Now you have to create the function doSomething

- (void)doSomething {

}

There ya go.. all done. The final product should look like this.

You can grab the source code here.

About mike
Currently works for OpenSky as a Senior Linux Admin. He has a wonderful wife Thanuja and 2 great dogs. His major side project is Photoblog.

Comments

4 Responses to “Add a navigation button”
  1. Turbolag says:

    When I compile the source code, and press the “Something” button on the navigation bar, the app crashes due to an uncaught exception. I am using the latest SDK.

  2. mikezupan says:

    Thanks for pointing that out.. That is what I get for using gutted code

    Here is the erroneous line

    action:@selector(doSomething:)] autorelease];

    We need to remove the : after doSomething

    action:@selector(doSomething)] autorelease];

    With the : it expects to be passed a argument.

    I also fixed the source code.

  3. jeffaudio says:

    What’s the difference between using NSLocalizedString(@”Something”, @”") and just writing @”Something”? I’ve tried both and they both seem to work fine.

  4. Joris Morger says:

    Wow, thank you… That really helped me out!

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!