Trying to programmatically add a button to a UINavigationController, but it never appears

I programmatically created some UINavigationControllers and added them to the UITabBarController. Everything seems to be working fine, but I wanted to add a cancel button to the navigation controller, but it never appears. I tried several ways, but I can’t influence the display of navigation elements in any way, and I used several 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 a button this way

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

I started to get upset, so I also tried some other things to see if I can influence anything, but to no avail

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

I tried to do this before and after the navigation controllers were added to the UITabBarController, and this did not help. I also tried rightBarButtonItem and tried to use initWithTitle: instead of initWithBarButtonSystemItem.

Will someone please light me up? It’s clear that I am doing it wrong.

+7
source share
3 answers

Try adding panel buttons to the loadView method of MyTableViewController , as shown below.

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

I think this should work.

+16
source

Have you tried customizing the button of the navigation item of the current view controller as follows:

 mtvc.navigationItem.leftBarButtonItem = closeButton; 
+4
source

If you need to do this in Swift 3.0, this is simple:

 let closeButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector({Your-viewController}.{close-method})) self.navigationItem.leftBarButtonItem = closeButton 
+2
source

All Articles