我是ios新手。我需要从应用程序委托中了解当前的视图控制器。我对此一无所知,也不知道如何实现它。我正在使用此代码来实现此功能,但它返回空值。
我点击了这个链接 -从应用程序委托获取当前视图控制器(模式是可能的) https://stackoverflow.com/questions/20485585/get-current-view-controller-from-the-app-delegate-modal-is-possible需要帮忙。
这是我用来查找用户最有可能与之交互的当前视图控制器的方法:
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
然后,每当我需要从应用程序中的任何位置使用当前视图控制器时,只需使用:
[UIViewController currentViewController]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)