判断当前窗口是否被加载了
if (self.isViewLoaded && self.view.window ) {
//Do Something
}
获取当前显示的ViewController
因为所有的ViewController都在Window里,而App都是在KeyWindow上,所以可以用以下代码获得
- (UIViewController *)getCurrentVC {
//1. 先找到KeyWindow
UIWindow * window = [[UIApplication sharedApplication] keyWindow];
//2. 正常情况下KeyWindow应该是在UIWindowLevelNormal,有Alert的时候KeyWindow就是Alert框
if (window.windowLevel != UIWindowLevelNormal)
{
//3. 如果不是UIWindowLevelNormal,那么找到UIWindowLevelNormal级别的Window
// 这里有个缺陷,因为UIWindowLevelNormal的不一定只有一个,虽然正常情况下只有一个
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow * tmpWin in windows)
{
if (tmpWin.windowLevel == UIWindowLevelNormal)
{
//找到了UIWindowLevelNormal的Window
window = tmpWin;
break;
}
}
}
//4. 判断RootViewController不是TabBarVC和NaviVC,且是ViewController
id result = window.rootViewController;
BOOL isViewController = ![result isKindOfClass:[UITabBarController class]] && ![result isKindOfClass:[UINavigationController class]] && [result isKindOfClass:[UIViewController class]];
//5. 进入递归循环,排除TabBarVC和NaviVC,以及进入PresentedVC继续递归
while (!isViewController) {
while ([result isKindOfClass:[UITabBarController class]]) {
UITabBarController *tempVC = result;
result = [tempVC selectedViewController];
}
while ([result isKindOfClass:[UINavigationController class]]) {
UINavigationController *tempVC = result;
result = [tempVC.viewControllers lastObject];
}
id presentedVC = [result presentedViewController];
if (presentedVC) {
result = presentedVC;
}
isViewController = ![result isKindOfClass:[UITabBarController class]] && ![result isKindOfClass:[UINavigationController class]] && [result isKindOfClass:[UIViewController class]];
}
return result;
}
该代码是加入了有Presented的VC就查到presented的,如果去掉present检查,可以查到除去model ViewController的第一个