iOS 獲取當(dāng)前正在顯示的ViewController

我們在非視圖類中想要隨時展示一個view時,需要將被展示的view加到當(dāng)前view的子視圖,或用當(dāng)前view presentViewController,或pushViewContrller,這些操作都需要獲取當(dāng)前正在顯示的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>

[原文轉(zhuǎn)載](http://stackoverflow.com/questions/24825123/get-the-current-view-controller-from-the-app-delegate

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容