如何从UINavigationController获取当前堆栈的顶部?

时间:2017-08-21 17:40:26

标签: ios swift delegates

这是一个UIViewController,其中创建了UINavigationController:

class Main_ProfileViewController: UIViewController { 

    var ProfileNavigationController = UINavigationController()

    buildProfileNavigationController()

    func buildProfileNavigationController() {
        let RootViewController = BlankViewController200()
        ProfileNavigationController = UINavigationController(rootViewController: RootViewController)
        self.view.addSubview(ProfileNavigationController.view)
    }

}



这是带有导航控制器委托的主容器类,以获取当前堆栈的顶部:

class MainContainerViewController: UIViewController {

    var currentTop: UIViewController?

}

extension MainContainerViewController: UINavigationControllerDelegate {

    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        currentTop = viewController
        print(currentTop)
    }

}



但是,没有任何内容打印到控制台。这是如何实现的?

1 个答案:

答案 0 :(得分:0)

要获得top viewController,您可以使用以下代码:

extension UIApplication {
    class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    }
}