如果您使用的是 UITabBarController,您可以通过以下方式获取对其子 UIViewControllers 的引用:
[myTabBarController objectAtIndex:index];
NSLog(@"Selected view controller class type: %@, selected index: %d", [myTabBarController selectedViewController], [myTabBarController selectedIndex]);
从零开始的索引方案遵循您设置的选项卡顺序,无论是通过编程还是通过 IB(最左边的选项卡 = 索引 0)。
因为您似乎正在搜索的 UIViewController 引用似乎是 rootViewController(因为您命名它的方式;“InitialViewController”),您也可以在您的 appDelegate 中尝试此操作。这需要 5 秒:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSLog(@"self.window.rootViewController = %@", NSStringFromClass([self.window.rootViewController class]));
UIViewController *myRootViewController = self.window.rootViewController;
}
让我知道这是否有效:)
无论您使用的是 UITabBarController 还是 UINavigationController,我确信其中之一就是您的 rootViewController。一旦你得到它的引用,剩下的就很简单了:
InitialViewController* myInitialViewController;
for (UIViewController *vc in [myRootViewController childViewControllers]) {
if([vc isKindOfClass:[InitialViewController class]]){
//Store this reference in a local/global variable or a property,
//or simply perform some logic on the vc pointer if you don't need to store it.
myInitialViewController = (InitialViewController *)vc; //Example & reminder to cast your reference
}
}
根据评论中发现的新细节进行编辑:
好的,在你的 topViewController 的 viewDidLoad 或 viewWillAppear 中运行这段代码:
//You have to import this class in order to reference it
#import "MESHomeViewController.h"
//Global variable for storing the reference (you can make this a property if you'd like)
MESHomeViewController *myHomeVC;
int i = 0;
for (UIViewController *vc in [self.slidingViewController childViewControllers]) {
NSLog(@"Current vc at index %d = %@", i, [vc class]);
if ([vc isKindOfClass:[MESHomeViewController class]]) {
NSLog(@"Found MESHomeViewController instance - [[self.slidingViewController childViewControllers] objectAtIndex:%d]", i);
myHomeVC = vc;
break;
}
i++;
}
看看那里是否有参考资料。如果是,您的控制台将打印出 HomeViewController 的类名。