从Appdelegate访问UITabBarController

8

我正在尝试从一个在UIWindow中的UIViewController中访问我的UiTabBarController,

由于它不是UITabBarController的一部分-使用 self.tabBarController.. 不起作用,因为它将为nil。

所以我尝试了这段代码:

BBAppDelegate *appDelegate = (BBAppDelegate *)[[UIApplication sharedApplication] delegate];

    UITabBarController *tabBarController = appDelegate.window.rootViewController.tabBarController;

当使用调试器逐步执行代码时,我可以看到appDelegate确实有一个tabBarController且不为null。然而,在下一行...

  UITabBarController *tabBarController = appDelegate.window.rootViewController.tabBarController;

这会导致tabBarController实例为空,而appDelegate中的tabBarController仍具有分配的内存地址,且不为空。

我做错了什么?

编辑

这是我的调试器外观:

enter image description here 谢谢!

编辑2

这是我设置侧边栏菜单的方式,它被添加到了rootViewController中。

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main_iPhone"
                                                         bundle: nil];

BBFilterViewController *loginController=[[UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil] instantiateViewControllerWithIdentifier:@"FilterViewController"];  UINavigationController *navController=[[UINavigationController alloc]initWithRootViewController:loginController];



self.tabBarController = [mainStoryboard instantiateViewControllerWithIdentifier: @"HomeScreen"];

MVYSideMenuOptions *options = [[MVYSideMenuOptions alloc] init];
options.contentViewScale = 1.0;
options.contentViewOpacity = 0.5;
options.shadowOpacity = 0.0;

MVYSideMenuController *sideBarController = [[MVYSideMenuController alloc]initWithMenuViewController:navController contentViewController:self.tabBarController options:options];


self.window.rootViewController = sideBarController;

[self.window.rootViewController addChildViewController:self.tabBarController];

[self.window makeKeyAndVisible];

你需要描述你的控制器设置。你是在应用程序委托中创建了你的控制器(或其中一些),还是在故事板中创建的? - rdelmar
在应用程序委托中只创建了一个控制器,其余的都在故事板中。 - Robert J. Clegg
2个回答

15

如果您将选项卡栏控制器设置为根视图控制器,您可以像这样访问它:

UITabBarController *tabBarController = (UITabBarController *)appDelegate.window.rootViewController;

//扩展

根据您问题的更新,您应该能够从最后一个子根视图控制器数组中获取对选项卡控制器的引用:

UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController.childViewControllers.lastObject;

这就是整个问题所在。我的rootViewController不是tabbarController。 - Robert J. Clegg
你的视图层次结构是什么? - Greg
在故事板中,tabBarController 是初始视图控制器。在应用代理中,我创建一个 uivwcontroller 并将其添加到 rootViewController。 - Robert J. Clegg
你能否发布一下添加uiviewcontroller到rootviewcontroller的代码? - Greg
1
请查看扩展帖子。 - Greg

-2

从您的调试器来看,我认为应该是 UITabBarController *tabBarController = appDelegate.tabBarController;


2
appDelegate.tabBarController 不存在。 - Robert J. Clegg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接