更新到13.5后,发现获取当前vc时,获取到的竟然是window。
以下是两种解决方案:
第一种:
UIWindow * window = [[UIApplication sharedApplication] keyWindow];
if(window.windowLevel != UIWindowLevelNormal) {
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow * tmpWininwindows) {
if(tmpWin.windowLevel == UIWindowLevelNormal) {
window = tmpWin;
break;
}
}
}
//从根控制器开始查找
UIViewController *rootVC = window.rootViewController;
UIViewController *activityVC =nil;
while (true) {
if([rootVC isKindOfClass:[UINavigationController class]]) {
activityVC = [(UINavigationController *)rootVC visibleViewController];
}elseif([rootVC isKindOfClass:[UITabBarController class]]) {
activityVC = [(UITabBarController *)rootVC selectedViewController];
}elseif(rootVC.presentedViewController) {
activityVC = rootVC.presentedViewController;
}else{
break;
}
rootVC = activityVC;
}
return rootVC;
第二种:
UIViewController *result =nil;
UIWindow * window = [[UIApplication sharedApplication] keyWindow];
if(window.windowLevel != UIWindowLevelNormal) {
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow * tmpWininwindows) {
if(tmpWin.windowLevel == UIWindowLevelNormal) {
window = tmpWin;
break;
}
}
}
//从根控制器开始查找
UIViewController *rootVC = window.rootViewController;
idnextResponder = [rootVC.view nextResponder];
NSLog(@"nextResponder---%@",nextResponder);
if([nextResponder isKindOfClass:[UINavigationController class]]) {
result = ((UINavigationController*)nextResponder).topViewController;
if([result isKindOfClass:[UITabBarController class]]) {
result = ((UITabBarController *)result).selectedViewController;
}
}elseif([nextResponder isKindOfClass:[UITabBarController class]]) {
result = ((UITabBarController*)nextResponder).selectedViewController;
if([result isKindOfClass:[UINavigationController class]]) {
result = ((UINavigationController *)result).topViewController;
}
}elseif([nextResponder isKindOfClass:[UIViewController class]]) {
result = nextResponder;
}else{
result = window.rootViewController;
if([result isKindOfClass:[UINavigationController class]]) {
result = ((UINavigationController *)result).topViewController;
if([result isKindOfClass:[UITabBarController class]]) {
result = ((UITabBarController *)result).selectedViewController;
}
}elseif([result isKindOfClass:[UIViewController class]]) {
result = nextResponder;
}
}
return result;
推荐第二种。