views:

1747

answers:

3

How to add a button to UINavigationBar programmatically?

A: 

Have a look at Apple's View Controller Programming Guide for iPhone OS, under Navigation Controllers.

I'm not sure if you want to show the 'standard' button or custom. Standard ones will be added automatically when you go from a view to 'next' view the new view will have a button to go back to the original view.

You can see in the above documentation how to add custom button under Using Custom Buttons and Views as Navigation Items.

stefanB
+5  A: 

Sample code to set the right button on a navigation bar.

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
    style:UIBarButtonSystemItemDone target:nil action:nil];
UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"Title"];
item.rightBarButtonItem = rightButton;
item.hidesBackButton = YES;
[bar pushNavigationItem:item animated:NO];
[rightButton release];
[item release];

But normally you would have a navigation controller, enabling you to write:

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
    style:UIBarButtonSystemItemDone target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightButton;
[rightButton release];
Mads Mobæk
A: 

The answers above are good, but I'd like to flesh them out with a few more tips:

If you want to modify the title of the back button (the arrow-y looking one at the left of the navigation bar) you MUST do it in the PREVIOUS view controller, not the one for which it will display. It's like saying "hey, if you ever push another view controller on top of this one, call the back button "Back" (or whatever) instead of the default."

If you want to hide the back button during a special state, such as while a UIPickerView is displayed, use self.navigationItem.hidesBackButton = YES; -- and remember to set it back when you leave the special state.

If you want to display one of the special symbolic buttons, use the form

initWithBarButtonSystemItem:target:action with a value like UIBarButtonSystemItemAdd

Remember, the meaning of that symbol is up to you, but be careful of the Human Interface Guidelines. Using UIBarButtonSystemItemAdd to mean deleting an item will probably get your application rejected.

Amagrammer