美文网首页
iOS如何获取当前最上层的UIViewController

iOS如何获取当前最上层的UIViewController

作者: 原来是泽镜啊 | 来源:发表于2020-01-03 21:53 被阅读0次

iOS开发当中时常会遇到需要获取当前控制器的需求(如:302重定向跳转,登录跳转等),本例已在项目中实践,小小分享,供参考。stackoverflow上的相关问答:

1、Get reference to top viewcontroller in iOS;
2、iPhone — How to find topmost view controller;

作为一个开发者,有一个学习的氛围跟一个交流圈子特别重要,这是一个我的iOS交流群:638302184,不管你是小白还是大牛欢迎入驻 ,分享BAT,阿里面试题、面试经验,讨论技术, 与2800+iOS开发者一起交流学习成长!

//获取当前最上层的控制器
-(UIViewController *) getTopMostController
{
    UIWindow *topWindow = [UIApplication sharedApplication].keyWindow;
    if (topWindow.windowLevel != UIWindowLevelNormal)
    {
        topWindow = [self returnWindowWithWindowLevelNormal];
    }

    UIViewController *topController = topWindow.rootViewController;
    if(topController == nil)
    {
        topWindow = [UIApplication sharedApplication].delegate.window;
        if (topWindow.windowLevel != UIWindowLevelNormal)
        {
            topWindow = [self returnWindowWithWindowLevelNormal];
        }
        topController = topWindow.rootViewController;
    }

    while(topController.presentedViewController)
    {
        topController = topController.presentedViewController;
    }

    if([topController isKindOfClass:[UINavigationController class]])
    {
        UINavigationController *nav = (UINavigationController*)topController;
        topController = [nav.viewControllers lastObject];

        while(topController.presentedViewController)
        {
            topController = topController.presentedViewController;
        }
    }

    return topController;
}

-(UIWindow *) returnWindowWithWindowLevelNormal
{
    NSArray *windows = [UIApplication sharedApplication].windows;
    for(UIWindow *topWindow in windows)
    {
        if (topWindow.windowLevel == UIWindowLevelNormal)
            return topWindow;
    }
    return [UIApplication sharedApplication].keyWindow;
}

作者:Haofree

相关文章

网友评论

      本文标题:iOS如何获取当前最上层的UIViewController

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