美文网首页
获取当前的ViewController

获取当前的ViewController

作者: NapoleonY | 来源:发表于2018-08-16 20:16 被阅读8次

概述

在某些view中,需要获取当前view所属的ViewController

方法

@implementation UIViewController (TopVC)

- (UIViewController *)getTopVC {
    UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = [self getTopVCFrom:rootVC];
    return topVC;
}

- (UIViewController *)getTopVCFrom:(UIViewController *)rootVC {
    UIViewController *topVC;
    if (rootVC.presentedViewController) {
        rootVC = rootVC.presentedViewController;
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        topVC = [self getTopVCFrom:[(UITabBarController *)rootVC selectedViewController]];//从它的`selectedViewController `中查找
    } else if ([rootVC isKindOfClass:[UINavigationController class]]) {
        topVC = [self getTopVCFrom:[(UINavigationController *)rootVC visibleViewController]];从它的`visibleViewController `中查找
    } else {
        topVC = rootVC;
    }
    
    return topVC;
}

新建一个UIViewController的category,增加一个方法- (UIViewController *)getTopVC

原理

keyWindow.rootViewController开始,追层向上查找:

  • 如果是UITabBarController,就从它的selectedViewController中查找
  • 如果是UINavigationController,就从它的visibleViewController中查找
    其中,此处此处使用visibleViewController原因为UINavigationControllervisibleViewController包含了导航控制器栈最上面的VC,也包含了被该UINavigationController模态(modally)展示的VC

Swift版本

extension UIViewController {
    func currentVC() -> UIViewController? {
        let vc = UIApplication.shared.keyWindow?.rootViewController
        guard vc != nil else {
            return nil
        }
        return currentTopVC(from: vc!)
    }
    
    // MARK: - Function
    private func currentTopVC(from destinateVC: UIViewController) -> UIViewController {
        var topVC = UIViewController()
        var rootVC = UIViewController()
        if destinateVC.presentedViewController != nil {
            rootVC = destinateVC.presentedViewController!
        } else {
            rootVC = destinateVC
        }
        
        if rootVC is UITabBarController {
            topVC = currentTopVC(from: (rootVC as! UITabBarController).selectedViewController!)
        } else if rootVC is UINavigationController {
            topVC = currentTopVC(from: (rootVC as! UINavigationController).visibleViewController!)
        } else {
            topVC = destinateVC
        }
        
        return topVC
    }
}

相关文章

网友评论

      本文标题:获取当前的ViewController

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