gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 07:59:53 29 4
gpt4 key购买 nike

我是 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com