问题
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