How can I get a reference to the current UINavigationController?

℡╲_俬逩灬. 提交于 2021-02-07 11:23:08

问题


In Objective-C, what is the best way of getting a reference to the current UINavigationController? I would like to gain access to it from any class that may not have a reference to a UIController, delegate, or anything else.

Is there an existing way to get the current UINavigationController? Should I add something to my application delegate, and retrieve that?


回答1:


As it turns out, you can get it, albeit with quite a bit of dot syntax, from any UIView/UIViewController descendant.

self.(view).window.rootViewController.navigationController;

If you are using an object that descends from any other class, the same is true, except you must go through UIApplication

[UIApplication sharedApplication].keyWindow.rootViewController.navigationController;

Of course, both of these break MVC in a big way, and it is definitely recommended that any logic that must touch the "default navigation controller" be added to the root view controller.




回答2:


Swift 4:

guard let navigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController else { return }


来源:https://stackoverflow.com/questions/14529817/how-can-i-get-a-reference-to-the-current-uinavigationcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!