iOS 获取当前window显示的控制器

可以在NSObject,UIView类里面使用,解决一些需要全局调用的函数里面跳转时报VC是nil的错,或者多层view弹出视图里push无响应的问题

- (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* navigationController = (UINavigationController*)rootViewController;

return [self topViewControllerWithRootViewController:navigationController.visibleViewController];

} else if (rootViewController.presentedViewController) {

UIViewController* presentedViewController = rootViewController.presentedViewController;

return [self topViewControllerWithRootViewController:presentedViewController];

} else {

return rootViewController;

}

}