UIViewController * findBestVC(UIViewController *vc) {
if (vc.presentedViewController) {
return findBestVC(vc.presentedViewController);
} else if ([vc isKindOfClass:[UISplitViewController class]]) {
UISplitViewController *sp = (UISplitViewController *)vc;
return sp.viewControllers.count > 0 ? findBestVC(sp.viewControllers.lastObject) : vc;
} else if ([vc isKindOfClass:[UINavigationController class]]) {
UINavigationController *na = (UINavigationController *)vc;
return na.viewControllers.count > 0 ? findBestVC(na.topViewController) : vc;
} else if ([vc isKindOfClass:[UITabBarController class]]) {
UITabBarController *ta = (UITabBarController *)vc;
return ta.viewControllers.count > 0 ? findBestVC(ta.selectedViewController) : vc;
}
return vc;
}
UIViewController * currentVC() {
UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
return findBestVC(rootVC);
}
只需要调用
UIViewController *VC = currentVC();