概述
在某些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
原因为UINavigationController
的visibleViewController
包含了导航控制器栈最上面的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
}
}
网友评论