UITabbarController动态更改项目

时间:2012-06-29 14:10:12

标签: uiviewcontroller uitabbarcontroller uitabbar uitabbaritem

我想在视图生命周期内编辑UITabbarItems。 背景是我有一个带登录视图的应用程序,根据用户是否是管理员,管理员TabbarItem应该是可见的。

我正在使用此代码初步在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];

我如何达到目标?提前致谢,亲切的问候,朱利安

1 个答案:

答案 0 :(得分: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];