本文介绍了iOS 获取当前的ViewController,分享给大家。具体如下
通过简单的判断[UIViewController class],就认定它是想要的控制器是不对的:
1
2
3
4
5
|
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。
提供一个完整的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
+ (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,有时候可能就会用到。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.jianshu.com/p/ee3c9b75d5f7?utm_source=tuicool&utm_medium=referral