美文网首页
UIView 中获取当前ViewController

UIView 中获取当前ViewController

作者: 世玉茹花 | 来源:发表于2019-09-27 13:42 被阅读0次

    自定义view中拿到当前VC。

    UIViewController *VC = [self getCurrentVC];

    - (UIViewController *)getCurrentVC
    
    {
        
        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        
        
        
        UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
        
        
        
        return currentVC;
        
    }
    
    - (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
    
    {
        
        UIViewController *currentVC;
        
        
        
        if ([rootVC presentedViewController]) {
            
            // 视图是被presented出来的
            
            
            
            rootVC = [rootVC presentedViewController];
            
        }
        
        
        
        if ([rootVC isKindOfClass:[UITabBarController class]]) {
            
            // 根视图为UITabBarController
            
            
            
            currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
            
            
            
        } else if ([rootVC isKindOfClass:[UINavigationController class]]){
            
            // 根视图为UINavigationController
            
            
            
            currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
            
            
            
        } else {
            
            // 根视图为非导航类
            
            
            
            currentVC = rootVC;
            
        }
        
        ```
        
        return currentVC;
        
    }

    相关文章

      网友评论

          本文标题:UIView 中获取当前ViewController

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