美文网首页IOS开发
获取当前viewController及当前view的viewCo

获取当前viewController及当前view的viewCo

作者: zwing | 来源:发表于2020-08-13 17:17 被阅读0次

    1. 获取当前viewController

    // 方法一:
    - (UIViewController *)getCurrentViewController
    {
        UIViewController *result = nil;
        // 获取默认的window
        UIWindow * window = [[UIApplication sharedApplication] keyWindow];
        // app默认windowLevel是UIWindowLevelNormal,如果不是,找到它。
        if (window.windowLevel != UIWindowLevelNormal) {
            NSArray *windows = [[UIApplication sharedApplication] windows];
            for(UIWindow * tmpWin in windows) {
                if (tmpWin.windowLevel == UIWindowLevelNormal) {
                    window = tmpWin;
                    break;
                }
            }
        }
        
        // 获取window的rootViewController
        result = window.rootViewController;
        while (result.presentedViewController) {
            result = result.presentedViewController;
        }
        if ([result isKindOfClass:[UITabBarController class]]) {
            result = [(UITabBarController *)result selectedViewController];
        }
        if ([result isKindOfClass:[UINavigationController class]]) {
            result = [(UINavigationController *)result visibleViewController];
        }
        return result;
    }
    
    // 方法二:
    UIViewController *getCurrentViewController(void) {
        UIWindow *window = [[UIApplication sharedApplication].delegate window];
        UIViewController *topViewController = [window rootViewController];
        
        while (true) {
            
            if (topViewController.presentedViewController) {
                
                topViewController = topViewController.presentedViewController;
                
            } else if ([topViewController isKindOfClass:[UINavigationController class]] && [(UINavigationController*)topViewController topViewController]) {
                
                topViewController = [(UINavigationController *)topViewController topViewController];
                
            } else if ([topViewController isKindOfClass:[UITabBarController class]]) {
                
                UITabBarController *tab = (UITabBarController *)topViewController;
                topViewController = tab.selectedViewController;
                
            } else {
                break;
            }
        }
        return topViewController;
    }
    

    2.获取当前view的viewController

    UIViewController *getViewControllerWithView(UIView *view){
        UIResponder *responder = view;
        while ((responder = [responder nextResponder]))
            if ([responder isKindOfClass: [UIViewController class]])
                return (UIViewController *)responder;
        return nil;
    }
    

    相关文章

      网友评论

        本文标题:获取当前viewController及当前view的viewCo

        本文链接:https://www.haomeiwen.com/subject/qgkidktx.html