首页 > 解决方案 > 如何从任何 ViewController 访问 CustomNavigationController 的方法?

问题描述

我创建了 CustomNavigationController 并添加了一些常用方法来向其中添加 UIBarButtonItems。现在我想从我的各种视图控制器中调用这些方法。

所以我的问题是-如何从任何其他 viewController 调用属于 customNavigationController 的方法

我可以通过以下方式在objectiveC中实现这一点:

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

其中“ addLogoutButtonWithVC ”是属于 CustomNavigationController 的方法。

我在 Swift 中尝试以上几行,但没有运气。

[注意:嵌入时,我已经在情节提要中将 NavigationController 替换为 CustomNavigationController,因此所有 navigationController 现在都指向 CustomNavigationController]

更新:在 CustomNavigationController 中声明 addLogoutButtonWithViewController 和 actionLogoutHandler

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

非常感谢这方面的任何帮助。

标签: iosswiftuinavigationcontrolleruinavigationbar

解决方案


它应该看起来像:

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


推荐阅读