简体   繁体   中英

Add RightButtonItem to navigation bar when displaying tabbarcontroller views

In my application I have tabbarcontroller that is not the first viewcontroller . It will open form a navigationcontroller .(by pushing it to stack from its parent)

Now I want to add a rightbarbuttonitem to the navigationbar of this view. I am using this code:

UIBarButtonItem *b= [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(actionBarButtonPressed)];
self.navigationController.navigationItem.rightBarButtonItem= b;

but it is not working-any buttons do not appear in the navigation bar. I searched about this but in all topic this codes has been answered as working solution. Maybe it should be different when using tabbar and navigationbar together. Does any one know any other working solutions.

Edit I add a break point ad last line and checked some variables. This is the result:

(lldb) po self.navigationController.navigationItem.rightBarButtonItem
error: property 'navigationItem' not found on object of type 'id'
error: 1 errors parsing expression
(lldb) po self.navigationController;
 nil
(lldb) po self.navigationItem;
<UINavigationItem: 0x8997070>
(lldb) 
(lldb) po self.navigationController.navigationItem.rightBarButtonItem
error: property 'navigationItem' not found on object of type 'id'
error: 1 errors parsing expression 

It seems that navigationController is nil and we directly should call navigationItem . So I changed the code but again not working. So I checked these variables:

(lldb) po self.navigationItem
<UINavigationItem: 0x8d789c0>
(lldb) po self.navigationItem.rightBarButtonItem
error: property 'rightBarButtonItem' not found on object of type 'id'
error: 1 errors parsing expression
(lldb) 

it seems that rightbarbuttonitem is not exist. So what should we do now?

The reason you can't change the right bar button item is because only your tab bar controller is in the navigation controller stack. The view controllers only have access to the tab bar controller.

So in order to have a custom navigation bar button, you have to add/set it in your UITabBarController .

If you'd like to have different UIBarButtons for each of your view controllers, there the delegate method tabBarController:didSelectViewController: where you can change the UIBarButtonItem based on the selected view controller.

If your view is: TabBarController ==> NavigationController ==> YourViewController

To set UIBarButtonItem like this:

self.tabBarController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(doSome)];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM