1.第一种方法
//方法调用
UIViewController *rootVc = [self topViewControllerWithRootViewController:[[[[UIApplication sharedApplication] delegate] window] rootViewController]];
// 实际方法处理
+ (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController
{
if ([rootViewController isKindOfClass:[UITabBarController class]]) {
UITabBarController *tabBarController = (UITabBarController *)rootViewController;
return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
} else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController* navigationController = (UINavigationController*)rootViewController;
return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
} else if (rootViewController.presentedViewController) {
UIViewController* presentedViewController = rootViewController.presentedViewController;
return [self topViewControllerWithRootViewController:presentedViewController];
} else {
return rootViewController;
}
}
2.第二种方法
//获取Window当前显示的ViewController
+ (UIViewController*)currentViewController{UIViewController* vc = [UIApplicationrootViewController];
while(1) {
if([vc isKindOfClass:[UITabBarControllerclass]]) {
vc = ((UITabBarController*)vc).selectedViewController;
}
if([vc isKindOfClass:[UINavigationControllerclass]]) {
vc = ((UINavigationController*)vc).visibleViewController;
}
if(vc.presentedViewController) {
vc = vc.presentedViewController;
} else {
break; }
}
returnvc;
}