在项目开发中,我们经常会遇到Controller中添加多个ChildController。在我们ChildController中我们要实现页面跳转,就必须要获取当前的主Controller。
我们可以为UIApplication
添加一个分类UIApplication+GYApplication.h
- (UIWindow *)mainWindow{
return self.delegate.window;
}
- (UINavigationController *)visibleNavigationController{
return [[self visibleViewController] navigationController];
}
- (UIViewController *)visibleViewController{
UIViewController *rootviewcontroller = [self.mainWindow rootViewController];
return [self getVisibleViewControllerFrom:rootviewcontroller];
}
//逐层遍历,获取当前所在控制器
- (UIViewController *)getVisibleViewControllerFrom:(UIViewController *)vc{
if ([vc isKindOfClass:[UINavigationController class]]) {
return [self getVisibleViewControllerFrom:[((UINavigationController *) vc)visibleViewController]];
}else if ([vc isKindOfClass:[UITabBarController class]]){
return [self getVisibleViewControllerFrom:[((UITabBarController *) vc)selectedViewController]];
}else{
if (vc.presentedViewController) {
return [self getVisibleViewControllerFrom:vc.presentedViewController];
}else{
return vc;
}
}
}
使用
UINavigationController *navi = [[UIApplication sharedApplication]visibleNavigationController];
[navi pushViewController:[[ViewController alloc]init] animated:YES];