iOS 获取当前的ViewController
通过简单的判断[UIViewController class]
,就认定它是想要的控制器是不对的:
if ([nextResponder isKindOfClass:[UIViewController class]]) {
result = nextResponder;
}else {
result = window.rootViewController;
}
因为:isKindOfClass:确定一个对象是否是一个类的成员,或者是派生自该类的成员。
根据iOS的类图可以知道,UIViewController类还有好几个派生类,需要我们去区分的就是UITabBarController
跟UINavigationController
,拿到它们不是我们想要的。
1)UITabBarController
通过属性viewControllers
持有多个viewController;
2)UINavigationController
通过压栈和出栈的方式持有或去除viewController;
3)UITableViewController就不用去判断了,它就是一个单个的viewController,而且更多的是手写创建tableView。
提供一个完整的方法:
+ (UIViewController *)getCurrentViewController {
UIViewController *result = nil;
UIWindow * window = [[UIApplication sharedApplication] keyWindow];
//app默认windowLevel是UIWindowLevelNormal,如果不是,找到它
if (window.windowLevel != UIWindowLevelNormal) {
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow * tmpWin in windows) {
if (tmpWin.windowLevel == UIWindowLevelNormal) {
window = tmpWin;
break;
}
}
}
id nextResponder = nil;
UIViewController *appRootVC = window.rootViewController;
//1、通过present弹出VC,appRootVC.presentedViewController不为nil
if (appRootVC.presentedViewController) {
nextResponder = appRootVC.presentedViewController;
}else{
//2、通过navigationcontroller弹出VC
NSLog(@"subviews == %@",[window subviews]);
UIView *frontView = [[window subviews] objectAtIndex:0];
nextResponder = [frontView nextResponder];
}
//1、tabBarController
if ([nextResponder isKindOfClass:[UITabBarController class]]){
UITabBarController * tabbar = (UITabBarController *)nextResponder;
UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
//或者 UINavigationController * nav = tabbar.selectedViewController;
result = nav.childViewControllers.lastObject;
}else if ([nextResponder isKindOfClass:[UINavigationController class]]){
//2、navigationController
UIViewController * nav = (UIViewController *)nextResponder;
result = nav.childViewControllers.lastObject;
}else{//3、viewControler
result = nextResponder;
}
return result;
}
从上面代码中,可以衍生出获取当前tabBarController、navigationController,有时候可能就会用到。