首页 > 代码库 > 【IOS】获取顶层UIViewController

【IOS】获取顶层UIViewController

Objective-c版本:

- (UIViewController *)appRootViewController
{
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}

Swift版本:

func AppRootViewController() -> UIViewController? {
    var topVC = UIApplication.sharedApplication().keyWindow?.rootViewController
    while topVC?.presentedViewController != nil {
        topVC = topVC?.presentedViewController
    }
    return topVC?
}


【IOS】获取顶层UIViewController