1

我想在视图生命周期中编辑UITabbarItems。 背景是我有一个应用程序与登录视图,并根据用户是否是管理员或管理员TabbarItem应该是否可见。UITabbarController动态更改项目

我使用这个代码在AppDelegate中最初创建的UITabBarController:

// AppDelegate.m 

settings = [[settingsViewController alloc] init]; 
settings.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Einstellungen" image:[UIImage imageNamed:@"settings.png"] tag:3]; 

self.tabBarController = [[UITabBarController alloc] init]; 
self.tabBarController.viewControllers = [NSArray arrayWithObjects:readState, friends, settings, nil]; 

当我尝试从另一个UIViewController中,没有任何反应和UITabbar仍然像从前那样后处理的项目。 其实我尝试了两种方法,我可以想像:

[[self tabBarController] setToolbarItems:[[[self tabBarController] toolbarItems] arrayByAddingObject:admin] animated:NO]; 
[[self tabBarController] setViewControllers:[[[self tabBarController] viewControllers] arrayByAddingObject:admin] animated:NO]; 

我怎样才能达到我的目标是什么?在此先感谢,以善良的问候,朱利安

回答

4

我想出了一个解决方案,我的问题。我真的不想导入AppDelegate,但似乎没有为UITabbarController的UIViewControllers自动设置tabbarController属性。

// generate an instance of the needed UIViewController 
adminViewController *admin = [[adminViewController alloc] init]; 
admin.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Admin" image:[UIImage imageNamed:@"admin.png"] tag:5]; 

// get the AppDelegate instance 
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 

// get the »viewControllers« array of the AppDelegates UITabbarController as mutable array 
NSMutableArray *viewControllersArray = [NSMutableArray arrayWithArray:[[appDelegate tabBarController] viewControllers]]; 
// insert the UITabbarItem of the needed UIViewController 
[viewControllersArray insertObject:admin atIndex:2]; 

// Finally tell the app delegates UITabbarController to set the needed viewControllers 
[[appDelegate tabBarController] setViewControllers:viewControllersArray animated:NO];