Search code examples
iosswiftuinavigationcontrolleruinavigationbar

How to access methods of CustomNavigationController from any ViewController?


I have created CustomNavigationController and added some common methods to add UIBarButtonItems to it. Now I want to call those methods from my various viewControllers.

So my question is - How to call methods which belongs to customNavigationController from any other viewController.

I can achieve this in objectiveC by following way :

[(CustomNavigationController *)self.navigationController addLogoutButtonWithVC:self actionLogoutHandler:@selector(actionLogoutHandler)];

where "addLogoutButtonWithVC" is method belongs to CustomNavigationController.

I am trying somewhat in above lines in Swift but no luck.

[Note : I have already replaced NavigationController with CustomNavigationController in storyboard when embedded in, so all navigationControllers are now pointing to CustomNavigationController only]

"Update : Declaration of addLogoutButtonWithViewController and actionLogoutHandler inside CustomNavigationController"

func addLogoutButtonWithViewController(viewCont : UIViewController , selLogout : Selector)  {
    currentController = viewCont
    var barButtonItem : UIBarButtonItem?
    barButtonItem = UIBarButtonItem(image: UIImage(named: "Logout.png"), style: UIBarButtonItemStyle.plain, target: self, action: Selector("actionLogoutHandler"))

   self.navigationController?.navigationItem.rightBarButtonItem = barButtonItem
}

@objc func actionLogoutHandler()  {
    print("Inside logout")
    currentController?.navigationController?.popToRootViewController(animated: true)
}

Any help in this regard is highly appreciated.


Solution

  • You should try my code as below.

    you need object of your navigation controller and use to set in button target.

        if let navigationcontroller = self.navigationController as? CustomNavigationController {
        navigationcontroller.addLogoutButton(withVC: self,
                            actionLogoutHandler:#selector(navigationcontroller.actionLogoutHandler(_:))
    }
    
        @objc func actionLogoutHandler()  {
        print("Inside logout")
        self.popToRootViewController(animated: true)
    }