[英]Accessing UITabBarController from UIVIewController
我正在开发一个基于 UITabbar 和视图层次结构的应用程序,如下所示。
UITabBarController ----> UINavigationController ----> UIViewController
我需要从 UIIVewController 访问 UITabBarController 。 但是以下属性总是返回 nil。
self.tabBarController 和 self.navigationController.tabBarController
有没有办法直接从子 viewController 访问 Tabbarcontroller 而不使用 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;
}
使用您正在使用的层次结构:
我可以毫无问题地从ViewController
访问UITabBarController
:
self.tabBarController
将您的自定义初始化移动到viewDidLoad
或viewDidAppear
然后对于 shure,您可以使用self.tabBarController
访问TabBarController
到达 TabBarController 的另一种方法是:
UITabBarController *tabBarController = (UITabBarController *)[[[UIApplication sharedApplication] delegate] window].rootViewController;
但在你的情况下完全没有必要。
编辑:
如果您正在使用 Xib,那么您已经在 AppDelegate 中以编程方式创建了一个 TabBarController。 我相信你有这样的事情:
self.tabBarController = [[UITabBarController alloc] init];
然后你可以在你的 ViewController 中调用它:
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
UITabBarController *tabBarController = appDelegate.tabBarController;
你做错了。
我有一个和你一样的应用程序。 我可以从viewDidLoad
访问标签viewDidLoad
。
尝试这个:
- (void)viewDidLoad {
[super viewDidLoad];
[self.tabBarController setSelectedIndex:1];
}
希望这可以帮助.. :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.