iOS 获取当前正在显示的ViewController

我们在非视图类中想要随时展示一个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

推荐阅读更多精彩内容