Adding a UIBarButtonItem programmatically to UINavigationBar

Crystal picture Crystal · Jul 17, 2011 · Viewed 42.4k times · Source

I dropped in a UINavigationBar in UIInterfaceBuilder. I present this view modally and just want a UIBackBarButton to return to my last view. I have an outlet and property to this UINavigationBar declared. I thought in my viewDidLoad method, I could create a UIBackButton like this:

UIBarButtonItem *backButton = 
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonItemStyleBordered 
                                              target:self 
                                              action:@selector(goBack)];
self.navigationItem.backBarButtonItem = backButton;
[backButton release];

But I do not see my UIBackBarButtonItem on the UINavigationBar. I think I am doing something wrong here since I don't think my UINavigationBar knows I'm trying to add this UIBackBarButtonItem to it in this way. Would I have to do create an NSArray, put the button in it, and setItems for the NavigationBar instead?

I'm confused on how the navigationItem property works vs the setItems of the UINavigationBar as well. Any help would be appreciated. Thanks!

Answer

Suhail Patel picture Suhail Patel · Jul 17, 2011

You are trying to set the Back Button Item in a modal view which doesn't add a backBarButtonItem. This what causes the Button (or any sort of back button for that matter) not to show. The backBarButtonItem is mainly for use with Pushed View Controllers which have a Back Button added from the parent (next item below) when you push a new view controller (top item). The Apple UINavigationItem Documentation says:

When this item is the back item of the navigation bar—when it is the next item below the top item—it may be represented as a back button on the navigation bar. Use this property to specify the back button. The target and action of the back bar button item you set should be nil. The default value is a bar button item displaying the navigation item’s title.

To get the Back Button on the left side like you wish, Try changing

self.navigationItem.backBarButtonItem = backButton;

to

self.navigationItem.leftBarButtonItem = backButton;