iOS 獲取View的當(dāng)前控制器 導(dǎo)航控制器 獲取當(dāng)前屏幕顯示的ViewController

場景

  • 為了解耦,誰的事情誰去做,那么在View的類中要push等等
  • 其他需要使用控制器的場景

1. 獲取當(dāng)前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. 獲取當(dāng)前View的導(dǎo)航控制器

+ (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;
}

獲取當(dāng)前屏幕顯示的ViewController

場景

  • 接收到推送時(shí),觸發(fā)事件,從當(dāng)前屏幕顯示的ViewController跳轉(zhuǎn)
  • ...
+ (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;
}

注:有時(shí)候你可能需要如下的方式獲取

UIViewController *currentVC = [[self class] getCurrentVC].childViewControllers[0].childViewControllers[0];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,227評論 25 708
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,229評論 4 61
  • 情緒就像一個(gè)根植于人類神經(jīng)系統(tǒng)的指令體系,成為人類心靈固有、自動的反應(yīng)傾向,對人類生存具有重大的意義。 在進(jìn)行決策...
    劉敏捷閱讀 960評論 0 0
  • OC: JNWSpringAnimation Facebook Pop RBBAnimation INTUAnim...
    tljackyi閱讀 952評論 0 1
  • 在地鐵1號線的末班車上,一直夢想成為作家的Jason,包里揣著kindle,iPad,與一本叫做《how to r...
    小進(jìn)叔閱讀 279評論 13 11