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.
在Objective-C中,获取对当前UINavigationController的引用的最佳方法是什么?我想从任何可能没有引用UIController,委托或其他任何内容的类中获取它。
Is there an existing way to get the current UINavigationController? Should I add something to my application delegate, and retrieve that?
是否有现有的方法来获取当前的UINavigationController?我应该向我的应用程序委托添加一些内容,并检索它吗?
2 个解决方案
#1
29
As it turns out, you can get it, albeit with quite a bit of dot syntax, from any UIView/UIViewController descendant.
事实证明,你可以从任何UIView / UIViewController后代获得它,尽管有相当多的点语法。
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
[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.
当然,这两者都会大大打破MVC,并且绝对建议将必须触摸“默认导航控制器”的任何逻辑添加到根视图控制器中。
#2
1
Swift 4:
斯威夫特4:
guard let navigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController else { return }
#1
29
As it turns out, you can get it, albeit with quite a bit of dot syntax, from any UIView/UIViewController descendant.
事实证明,你可以从任何UIView / UIViewController后代获得它,尽管有相当多的点语法。
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
[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.
当然,这两者都会大大打破MVC,并且绝对建议将必须触摸“默认导航控制器”的任何逻辑添加到根视图控制器中。
#2
1
Swift 4:
斯威夫特4:
guard let navigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController else { return }