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];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,049评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,194评论 4 61
  • 情绪就像一个根植于人类神经系统的指令体系,成为人类心灵固有、自动的反应倾向,对人类生存具有重大的意义。 在进行决策...
    刘敏捷阅读 4,483评论 0 0
  • OC: JNWSpringAnimation Facebook Pop RBBAnimation INTUAnim...
    tljackyi阅读 4,429评论 0 1
  • 在地铁1号线的末班车上,一直梦想成为作家的Jason,包里揣着kindle,iPad,与一本叫做《how to r...
    小进叔阅读 1,950评论 13 11