在开发过程中,我们经常需要获取当前 window, rootViewController, 以及当前 ViewController 的需求,来实现跳转或者其他业务需求. 如果 .m 实现不是在当前视视图情况下, 或者在子视图中,我们需要快速的获取到当前控制器,.
我们想要与控制器无耦合的情况下, 想要直接获取到当前控制器, 基本都是通过 rootViewController 来查找的, 通过上面的方法拿到 rootViewControoler 之后, 我们先看 presentedViewController, 因为控制器呈现出来的方式有 push 与 present, 我们先查看它是否是 present 出来的, 如果是则通过此属性能找到 present 出来的当前控制器, 然后在检查是否属于 UINavigationControler 或 UITabBarController ,如果是则通过查找其子控制器里面最顶层或者其正在选择的控制器。
最后在判断当前控制器是否有子控制器的情况, 如果有则取其子控制器最顶层, 否则当前控制器就是其本身。
+ (UIViewController *)xs_getCurrentViewController{
UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
NSAssert(window, @"The window is empty");
//获取根控制器
UIViewController* currentViewController = window.rootViewController;
//获取当前页面控制器
BOOL runLoopFind = YES;
while (runLoopFind){
if (currentViewController.presentedViewController) {
currentViewController = currentViewController.presentedViewController;
} else if ([currentViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController* navigationController = (UINavigationController* )currentViewController;
currentViewController = [navigationController.childViewControllers lastObject];
} else if ([currentViewController isKindOfClass:[UITabBarController class]]){
UITabBarController* tabBarController = (UITabBarController* )currentViewController;
currentViewController = tabBarController.selectedViewController;
} else {
NSUInteger childViewControllerCount = currentViewController.childViewControllers.count;
if (childViewControllerCount > 0) {
currentViewController = currentViewController.childViewControllers.lastObject;
return currentViewController;
} else {
return currentViewController;
}
}
} return currentViewController;
}
这里主要是查找当前 应用程序基于 UITabBarController 和 UINavigationControler 下管理的视图控制器, 如果还有其他控制器则需要添加 if 条件来进行判断。