获取最顶层的视图控制器 iOS

1、获取当前所展示的控制器:

//需要获取到显示在最上面的viewController
- (UIViewController *)theTopviewControler{
    //获取根控制器
    UIViewController *rootVC = [[UIApplication sharedApplication].delegate window].rootViewController;
    
    UIViewController *parent = rootVC;
    //遍历 如果是presentViewController
    while ((parent = rootVC.presentedViewController) != nil ) {
        rootVC = parent;
    }
   
    while ([rootVC isKindOfClass:[UINavigationController class]]) {
        rootVC = [(UINavigationController *)rootVC topViewController];
    }
    return rootVC;
}

 

2.找到当前视图的父视图控制器

- (UIViewController *)viewController {

    for(UIView* next = [self superview]; next; next = next.superview) {

        UIResponder*nextResponder = [next nextResponder];

        if ([nextResponder isKindOfClass:[UIViewController class]]) {

            return(UIViewController*)nextResponder;

        }
    }

    return nil;
}

 

posted @ 2022-04-18 21:09  黄增松  阅读(486)  评论(0编辑  收藏  举报