Unable to add barbuttonitem to navigation controller

264 views Asked by At

I would like to integrate both navigation controller and tab bar controller in my project.But I am unable to add right barbutton to the navigation controller.

I have attached the screenshot of the storyboard enter image description here

What I have done is I have added navigation controller to login screen and this time I am able to add barbuttonitem both by adding code as well as by dragging barbuttonitem to navigation controller.

let addBtn = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
self.navigationItem.rightBarButtonItem = addBtn

Problem I am facing is after adding Tab bar controller I am unable to add rightbarbutton both by code as well as by dragging to the navigation controller. please help me.

2

There are 2 answers

3
RajeshKumar R On BEST ANSWER

When a ViewController is embedded in a NavigationController you use

self.navigationItem.rightBarButtonItem = addBtn

In your project Detail Screen isn't embedded in NavigationController directly. Detail Screen is embedded in TabBarController, TabBarController is embedded in NavigationController. So you should use

self.tabBarController?.navigationItem.rightBarButtonItem = addBtn

But this addBtn will be visible in all view controllers which are embedded in the TabBarController.

If you want to add the rightBarButton for only one viewcontroller, then embed the Detail Screen in a new NavigationController. Then you can add rightBarButton using

self.navigationItem.rightBarButtonItem = addBtn
0
Faruk On

You should be sure parent returns the top child controller of UINavigationController. In my case

parent?.parent?.navigationItem.right... 

did the trick.

If you reuse the controller -as embedded or not- which you want add items to navigationItem, following example will work. However some logical changes may be needed.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    guard parent is UINavigationController else {
        parent?.parent?.navigationItem.rightBarButtonItem = UIBarButtonItem()
        return
    }
    navigationItem.rightBarButtonItem = UIBarButtonItem()
    
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    guard parent is UINavigationController else {
        parent?.parent?.navigationItem.rightBarButtonItem = nil
        return
    }
    navigationItem.rightBarButtonItem = nil
}