1. 程式人生 > >獲取頂層的ViewController

獲取頂層的ViewController

- (UIViewController *)topViewController {
    //第一步:獲取根檢視
    UIViewController *resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    
    //第二步:從根檢視一直向上尋找頂層檢視
    //注:A控制器跳轉到B控制器,A.presentedViewController = B
    while (resultVC.presentedViewController != nil) {
        //判斷控制器的型別
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

- (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        // 型別為導航欄控制器,返回棧頂控制器
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        // 型別為分欄控制器,返回當前的控制器
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}