美文网首页
iOS 获取当前window显示的控制器

iOS 获取当前window显示的控制器

作者: 9e5f2143c765 | 来源:发表于2019-06-25 09:21 被阅读0次

    可以在NSObject,UIView类里面使用,解决一些需要全局调用的函数里面跳转时报VC是nil的错,或者多层view弹出视图里push无响应的问题

    - (UIViewController*)topViewController
    
    {
    
    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    
    }
    
    - (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController
    
    {
    
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
    
    UITabBarController *tabBarController = (UITabBarController *)rootViewController;
    
    return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
    
    UINavigationController* navigationController = (UINavigationController*)rootViewController;
    
    return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    
    } else if (rootViewController.presentedViewController) {
    
    UIViewController* presentedViewController = rootViewController.presentedViewController;
    
    return [self topViewControllerWithRootViewController:presentedViewController];
    
    } else {
    
    return rootViewController;
    
    }
    
    }
    

    相关文章

      网友评论

          本文标题:iOS 获取当前window显示的控制器

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