美文网首页专注iOS开发工程项目需要的功能iOS实战
iOS 获取当前正在显示的ViewController

iOS 获取当前正在显示的ViewController

作者: 代码干货 | 来源:发表于2015-09-21 16:43 被阅读5230次

    我们在非视图类中想要随时展示一个view时,需要将被展示的view加到当前view的子视图,或用当前view presentViewController,或pushViewContrller,这些操作都需要获取当前正在显示的ViewController。
    UIViewController+Utils.h
    <pre>

    import <UIKit/UIKit.h>

    @interface UIViewController (Utils)

    +(UIViewController*) currentViewController;
    @end
    </pre>

    UIViewController+Utils.m
    <pre>

    import "UIViewController+Utils.h"

    @implementation UIViewController (Utils)
    +(UIViewController) findBestViewController:(UIViewController)vc {
    if (vc.presentedViewController) {
    // Return presented view controller
    return [UIViewController findBestViewController:vc.presentedViewController];

    } else if [vc isKindOfClass:[UISplitViewController class]]) {
    
        // Return right hand side
        UISplitViewController* svc = (UISplitViewController*) vc;
        if (svc.viewControllers.count > 0)
            return [UIViewController findBestViewController:svc.viewControllers.lastObject];
        else
            return vc;
    
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
    
        // Return top view
        UINavigationController* svc = (UINavigationController*) vc;
        if (svc.viewControllers.count > 0)
            return [UIViewController findBestViewController:svc.topViewController];
        else
            return vc;
    
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
    
        // Return visible view
        UITabBarController* svc = (UITabBarController*) vc;
        if (svc.viewControllers.count > 0)
            return [UIViewController findBestViewController:svc.selectedViewController];
        else
            return vc;
    
    } else {
    
        // Unknown view controller type, return last child view controller
        return vc;
    
    }
    

    }

    +(UIViewController*) currentViewController {

    // Find best view controller
    UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    return [UIViewController findBestViewController:viewController];
    

    }

    @end
    </pre>

    [原文转载](http://stackoverflow.com/questions/24825123/get-the-current-view-controller-from-the-app-delegate

    相关文章

      网友评论

      • manajay:我也是想问 alertViewController 怎么办
      • ChasonTse:通篇代码都缺少 *, 一点都不规范
        代码干货:@ChasonTse 贴到简书上,默认就给省略啦:joy:
      • 红色小星:如果用户页面有个alertview 获取的话 就是 alertviewcontroller了,这时候我无法push啊 可以跳过这个alertviewcontroller吗 获取前一个controller吗
      • 响尾猫:好东西
      • 友友果果:不错!
      • 半尺尘:好...

      本文标题:iOS 获取当前正在显示的ViewController

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