陈斌彬的技术博客

Stay foolish,stay hungry

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?
}