欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS 获取当前正在显示的ViewController

程序员文章站 2024-01-14 22:59:52
...

我们在非视图类中想要随时展示一个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://*.com/questions/24825123/get-the-current-view-controller-from-the-app-delegate

上一篇: HelloWord

下一篇: HelloWord