iOS 获取View的当前控制器 导航控制器 获取当前屏幕显示的ViewController

场景

  • 为了解耦,谁的事情谁去做,那么在View的类中要push等等
  • 其他需要使用控制器的场景

1. 获取当前View的ViewController

+ (UIViewController *)viewControllerFromView:(UIView *)view {
    for (UIView *next = [view superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

2. 获取当前View的导航控制器

+ (UINavigationController *)navigationControllerFromView:(UIView *)view {
    for (UIView *next = [view superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UINavigationController class]]) {
            return (UINavigationController *)nextResponder;
        }
    }
    return nil;
}

获取当前屏幕显示的ViewController

场景

  • 接收到推送时,触发事件,从当前屏幕显示的ViewController跳转
  • ...
+ (UIViewController *)getCurrentVC {
    
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    if (!window) {
        return nil;
    }
    UIView *tempView;
    for (UIView *subview in window.subviews) {
        if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
            tempView = subview;
            break;
        }
    }
    if (!tempView) {
        tempView = [window.subviews lastObject];
    }
    
    id nextResponder = [tempView nextResponder];
    while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
        tempView =  [tempView.subviews firstObject];
        
        if (!tempView) {
            return nil;
        }
        nextResponder = [tempView nextResponder];
    }
    return  (UIViewController *)nextResponder;
}

注:有时候你可能需要如下的方式获取

UIViewController *currentVC = [[self class] getCurrentVC].childViewControllers[0].childViewControllers[0];

你可能感兴趣的:(iOS 获取View的当前控制器 导航控制器 获取当前屏幕显示的ViewController)