ios - 从应用委托(delegate)获取当前 View Controller

标签 ios objective-c delegates appdelegate

我是 ios 的新手。我需要从应用程序委托(delegate)中了解当前的 View Controller 。我对此一无所知,也不知道要实现它。我正在使用这段代码来实现它,但它返回空值。 我点击了这个链接- Get current view controller from the app delegate (modal is possible) 需要帮助。

最佳答案

这是我用来查找用户最有可能与之交互的当前 View Controller 的方法:

UIViewController+Utils.h

#import <UIKit/UIKit.h>

@interface UIViewController (Utils)

+(UIViewController*) currentViewController;

@end

UIViewController+Utils.m

#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

然后每当我需要从应用程序中的任何地方使用当前 View Controller 时,只需使用:

[UIViewController currentViewController]

关于ios - 从应用委托(delegate)获取当前 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24825123/

相关文章:

ios - 根据我的媒体查询禁用 JS

ios - Rails 4 iOS 身份验证和授权

ios - 需要有关 AVAssetExportSession 的帮助

ios - 从 UITableViewCell 到 ViewController 的按钮操作

swift - 如何在 Swift 中对委托(delegate)方法的异步调用进行单元测试?

iOS TTTAttributedLabel 委托(delegate) didSelectLinkWithURL 没有被调用

iOS - 使用 dealloc 删除观察者

ios - Fabric Crashlytics 中缺少版本

ios - UIButton 标题和图像的不同对齐方式

ios - Facebook Audience Network ios FBAdView 宽度