iOS 获取最上层视图控制器

Objective-C:

.h文件

#import 
NS_ASSUME_NONNULL_BEGIN
@interface UIViewController (TopVC)
+ (UIViewController *)TopVC;
@end
NS_ASSUME_NONNULL_END

.m文件

#import "UIViewController+TopVC.h"
@implementation UIViewController (TopVC)
+ (UIViewController *)TopVC {
    UIViewController *resultVC = [self _topVC:[UIApplication sharedApplication].keyWindow.rootViewController];
    while (resultVC.presentingViewController != nil) {
        return [self _topVC:resultVC.presentingViewController];
    }
    return resultVC;
}
+ (UIViewController *)_topVC:(UIViewController *)vc {
    if ([vc isKindOfClass: [UINavigationController class]]) {
        return [self _topVC:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topVC:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
}
@end

Swift:

import UIKit

/** 返回顶视图控制器 */
public var topVC: UIViewController?  {
    var resultVC: UIViewController? = _topVC(UIApplication.shared.keyWindow?.rootViewController)
    while resultVC?.presentedViewController != nil {
        resultVC = _topVC(resultVC?.presentedViewController)
    }
    return resultVC
}
func _topVC(_ vc: UIViewController?) -> UIViewController? {
    if vc is UINavigationController {
        return _topVC((vc as? UINavigationController)?.topViewController)
    }
    else if vc is UITabBarController {
        return _topVC((vc as? UITabBarController)?.selectedViewController)
    }
    else {
        return vc
    }
}

你可能感兴趣的:(iOS 获取最上层视图控制器)