iOS 獲取view當前UIViewController的幾種方法

  1. 經過響應鏈的方法
@implementation UIView (SYGetController)

- (UIViewController *)currentController {
    UIResponder *next = [self nextResponder];
    do {
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        next = [next nextResponder];
    } while (next != nil);
    return nil;
}
@end
複製代碼
  1. 利用遞歸的思想查找當前視圖控制器
+ (UIViewController *)currentViewController {
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentVC = [self _findCurrentShowingViewControllerFromVC:vc];
    return currentVC;
}

+ (UIViewController *)_findCurrentShowingViewControllerFromVC:(UIViewController *)vc {
    UIViewController *currentVC;
    if ([vc presentedViewController]) {
        //判斷當前根視圖有沒有present視圖出來
        UIViewController *nextVC = [vc presentedViewController];
        currentVC = [self _findCurrentShowingViewControllerFromVC:nextVC];
        
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        //判斷當前根視圖是UITabBarController
        UIViewController *nextVC = [(UITabBarController*)vc selectedViewController];
        currentVC = [self _findCurrentShowingViewControllerFromVC:nextVC];
        
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        //判斷當前根視圖是UINavigationController
        UIViewController *nextVC = [(UINavigationController *)vc visibleViewController];
        currentVC = [self _findCurrentShowingViewControllerFromVC:nextVC];
    }else {
        currentVC = vc;
    }
    return vc;
}
複製代碼
  1. 遍歷的方法獲取
+ (UIViewController *)_findCurrentShowingViewControllerFromVC:(UIViewController *)vc {
    while (1) {
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController *)vc).selectedViewController;
        } else if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController *)vc).visibleViewController;
        } else if (vc.childViewControllers.count > 0) {
            vc = vc.childViewControllers.lastObject;
        } else {
            break;
        }
    }
    return vc;
}
複製代碼

補充:presentedViewControllerpresentingViewController 假如從控制器A經過present方式跳轉到B,則ApresentedViewController就是B,BpresentingViewController就是Abash

相關文章
相關標籤/搜索