Search code examples
iphoneobjective-ciosuinavigationcontrolleruibarbuttonitem

Trying to programmatically add a button to UINavigationController but it never shows up


I've programmatically created some UINavigationControllers and added them to a UITabBarController. Everything seems to work fine but I wanted to add a cancel button to the navigation controller but it never shows up. I've tried multiple ways but I can't seem to affect the display of the navigation items at all and I've followed multiple examples from here and other sites but nothing happens.

MyTableViewController *mtvc = [[MyTableViewController alloc] init]; 
UINavigationController *myNavController = [[[UINavigationController alloc] initWithRootViewController:mtvc] autorelease];
myNavController.navigationBar.barStyle = UIBarStyleBlackOpaque;  // this works
[mtvc release];

// TODO: figure out why added buttons aren't showing
UIBarButtonItem *closeButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(shutDown)] autorelease]; 
myNavController.navigationItem.leftBarButtonItem = closeButton;  // never shows up

I also tried adding the button this way

[myNavController.navigationItem setLeftBarButtonItem:closeButton animated:NO];  // also doesn't do anything

I started getting frustrated so I also tried some other things just to see if I could affect anything, but to no avail

myNavController.title = @"test";  // does nothing

I've tried doing it before and after the navigations controllers were added to the UITabBarController and that didn't help. I've also tried rightBarButtonItem and tried using initWithTitle: instead of initWithBarButtonSystemItem.

Would someone please illuminate me? Clearly, I'm doing this the wrong way.


Solution

  • Try adding the bar buttons in the loadView method of MyTableViewController like the follwing.

    UIBarButtonItem *closeButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(shutDown)] autorelease]; 
    self.navigationItem.leftBarButtonItem = closeButton;
    

    I guess that should work.