Add a navigation button

August 8, 2008    Intro Programming

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", @"")
                                   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.

comments powered by Disqus