iOS 获取view当前UIViewController的几种方法

  1. 经过响应链的方法
@implementation UIView (SYGetController)

- (UIViewController *)currentController {
    UIResponder *next = [self nextResponder];
    do {
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        next = [next nextResponder];
    } while (next != nil);
    return nil;
}
@end
复制代码
  1. 利用递归的思想查找当前视图控制器
+ (UIViewController *)currentViewController {
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentVC = [self _findCurrentShowingViewControllerFromVC:vc];
    return currentVC;
}

+ (UIViewController *)_findCurrentShowingViewControllerFromVC:(UIViewController *)vc {
    UIViewController *currentVC;
    if ([vc presentedViewController]) {
        //判断当前根视图有没有present视图出来
        UIViewController *nextVC = [vc presentedViewController];
        currentVC = [self _findCurrentShowingViewControllerFromVC:nextVC];
        
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        //判断当前根视图是UITabBarController
        UIViewController *nextVC = [(UITabBarController*)vc selectedViewController];
        currentVC = [self _findCurrentShowingViewControllerFromVC:nextVC];
        
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        //判断当前根视图是UINavigationController
        UIViewController *nextVC = [(UINavigationController *)vc visibleViewController];
        currentVC = [self _findCurrentShowingViewControllerFromVC:nextVC];
    }else {
        currentVC = vc;
    }
    return vc;
}
复制代码
  1. 遍历的方法获取
+ (UIViewController *)_findCurrentShowingViewControllerFromVC:(UIViewController *)vc {
    while (1) {
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController *)vc).selectedViewController;
        } else if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController *)vc).visibleViewController;
        } else if (vc.childViewControllers.count > 0) {
            vc = vc.childViewControllers.lastObject;
        } else {
            break;
        }
    }
    return vc;
}
复制代码

补充:presentedViewControllerpresentingViewController 假如从控制器A经过present方式跳转到B,则ApresentedViewController就是B,BpresentingViewController就是Abash

相关文章
相关标签/搜索