- (UIViewController*)getpresentVC:(UIWindow *)window{ if ([window.rootViewController class]==[UITabBarController class]) { UITabBarController *tabBarController = (UITabBarController*)window.rootViewController; UINavigationController *navi = [tabBarController.viewControllers lastObject]; NSLog(@"%d",navi.viewControllers.count); UIViewController *VC =[navi.viewControllers lastObject]; if (!VC.presentedViewController) { return VC.presentedViewController; }else{ return VC; } }else{ return window.rootViewController; } }
或者使用递归调用
- (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; } }