iLearner
iLearner

Reputation: 1680

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.

Upvotes: 0

Views: 89

Answers (3)

Rakesh Patel
Rakesh Patel

Reputation: 1701

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)
}

Upvotes: 1

CZ54
CZ54

Reputation: 5586

It should looks like:

if let nav = self.navigationController as? CustomNavigationController { nav.addLogoutButton(withVC: self, actionLogoutHandler:#selector(CustomNavigationController .actionLogoutHandler(_:)) }

Upvotes: 1

gorzki
gorzki

Reputation: 433

Try this:

guard let customNavigationController = self.navigationController as? CustomNavigationController else { return }
customNavigationController.addLogoutButtonWithVC()

Upvotes: 0

Related Questions