iosswiftuibarbuttonitemrightbarbuttonitem

Unable to add barbuttonitem to navigation controller


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.


Solution

  • 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