问题描述
我正在开发一个基于UITabbar和视图层次结构的应用程序,如下所示。
I am developing an application based on UITabbar and the view hierarchy as follows.
UITabBarController ----> UINavigationController ----> UIViewController
UITabBarController ----> UINavigationController ----> UIViewController
我需要从UIIVewController访问UITabBarController。但是以下属性总是返回nil。
I need to access the UITabBarController from the UIIVewController . But following properties always returns nil.
self.tabBarController和self.navigationController.tabBarController
self.tabBarController and self.navigationController.tabBarController
有没有办法直接从子viewController访问Tabbarcontroller而不使用AppDelegate?
Is there a way to access the Tabbarcontroller directly from a child viewController without using the AppDelegate ?
@implementation HomeViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
self.title = @"Home";
self.navigationItem.title = @"Home";
self.tabBarItem.image = [UIImage imageNamed:@"TabBarHome"];
UITabBarController *tab = self.tabBarController;
UITabBarController *tab1 = self.navigationController.tabBarController;
UITabBarController *tab2 = self.navigationController.presentingViewController;
}
return self;
}
推荐答案
随着你的层次结构使用:
With the hierachy that you are using:
我可以从 ViewController
中轻松访问 UITabBarController
:
I can acces without problem the UITabBarController
from the ViewController
with:
移动你的自定义初始化为 viewDidLoad
或 viewDidAppear
Move your Custom initialization to viewDidLoad
or viewDidAppear
然后为舒尔您可以使用 self.tabBarController访问
TabBarController
Then for shure you can access TabBarController
with self.tabBarController
另一个到达你的TabBarController的方法是:
Another way to arrive to your TabBarController is:
UITabBarController *tabBarController = (UITabBarController *)[[[UIApplication sharedApplication] delegate] window].rootViewController;
但在你的情况下完全没必要。
But it is totally unnecessary in your case.
编辑:
如果您正在使用Xib,那么您已经在AppDelegate中以编程方式创建了一个TabBarController。我相信你有类似的东西:
If you are working with Xib, then you has been created a TabBarController programmatically in your AppDelegate. I'm sure you have something like:
然后你可以在你的ViewController中调用它:
Then you can call it in your ViewController:
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]
UITabBarController *tabBarController = appdelegate.tabBarController;
这篇关于从UIVIewController访问UITabBarController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!