//寻找最外层控制器
- (UIViewController *)keyVc {
UIViewController *rootVc = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *keyVc = rootVc;
while ([keyVc presentedViewController]) {
keyVc = [keyVc presentedViewController];
}
return keyVc;
}
//寻找最上层控制器
- (UIViewController*)topViewController {
return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.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* nav = (UINavigationController*)rootViewController;
return [self topViewControllerWithRootViewController:nav.visibleViewController];
} else if (rootViewController.presentedViewController) {
UIViewController* presentedViewController = rootViewController.presentedViewController;
return [self topViewControllerWithRootViewController:presentedViewController];
} else {
return rootViewController;
}
}
网友评论