相信大家做iOS项目应该都会有同样需求,需要一个通用方法获取屏幕当前正在显示的ViewController,比如说,我之前封装一个分享的框架,需要知道当前屏幕显示VC跳转到系统短信界面,如果直接传入当前VC可以满足这个需求,但作为一个通用框架,如果不需要外界传递能够直接获取,感觉代码会优雅很多。
1.获取RootViewController
下面是Apple官方文档说明
The root view controller provides the content view of the window. Assigning a view controller to this property (either programmatically or using Interface Builder) installs the view controller’s view as the content view of the window. If the window has an existing view hierarchy, the old views are removed before the new ones are installed.
rootViewController的设定通常会在设置keyWindow的时候遇到, 表示该UIWindow的最底层的UIViewController
UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
UIViewController *rootVC = keyWindow.rootViewController;
2.获取currentViewController
无论项目RootViewController是UIViewController、UINavigationController或者UITabBarController,无论当前页面经过多少次Push或者Present出来,下面方法都可以准确获取
while (rootVC.presentedViewController) {
rootVC = rootVC.presentedViewController;
if ([rootVC isKindOfClass:[UITabBarController class]]) {
rootVC = ((UITabBarController *)rootVC).selectedViewController;
} else if ([rootVC isKindOfClass:[UINavigationController class]]){
rootVC = ((UINavigationController *)rootVC).visibleViewController;
}
}
if ([rootVC isKindOfClass:[UITabBarController class]]) {
rootVC = ((UITabBarController *)rootVC).selectedViewController;
} else if ([rootVC isKindOfClass:[UINavigationController class]]){
rootVC = ((UINavigationController *)rootVC).visibleViewController;
}
return rootVC;
如果大家有更好的获取当前VC方式,欢迎提出,谢谢!