美文网首页UIViewController
iOS 获取view当前UIViewController的几种方

iOS 获取view当前UIViewController的几种方

作者: Devbrave | 来源:发表于2019-06-14 13:58 被阅读0次
怀梦致远
  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就是A

相关文章

网友评论

    本文标题:iOS 获取view当前UIViewController的几种方

    本文链接:https://www.haomeiwen.com/subject/kpxefctx.html