美文网首页
根据view查找控制器、获取当前window的顶层控制器

根据view查找控制器、获取当前window的顶层控制器

作者: x_tcan | 来源:发表于2018-05-09 10:45 被阅读69次

//根据view查找控制器

UIViewController *controller = nil;
for (UIView *superV = view.superview; superV; superV = superV.superview) {
    UIResponder *nextResponder = [superV nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        controller = (UIViewController *)nextResponder;
        break;
    }
}

//获取当前window的顶层控制器

- (UIViewController *)topViewController {
      UIViewController *resultVC;
      resultVC = [self _topViewController:[[UIApplication sharedApplication].delegate.window rootViewController]];
      while (resultVC.presentedViewController) {
          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;
}

相关文章

网友评论

      本文标题:根据view查找控制器、获取当前window的顶层控制器

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