iOS获取最顶层ViewController
1.获取当前屏幕显示的 Viewcontroller 案例源码
2.UIApplication 的简析
3.KeyWindow 的简析
4.rootViewController 的简析
5.PresentedViewController 的简析
1 获取当前屏幕显示的 Viewcontroller
//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
///下文中有分析
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
return currentVC;
- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
UIViewController *currentVC;
if ([rootVC presentedViewController]) {
// 视图是被presented出来的
rootVC = [rootVC presentedViewController];
if ([rootVC isKindOfClass:[UITabBarController class]]) {
// 根视图为UITabBarController
currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
} else if ([rootVC isKindOfClass:[UINavigationController class]]){
// 根视图为UINavigationController
currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
} else {
// 根视图为非导航类
currentVC = rootVC;