1

我想在视图生命周期内编辑 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];

我怎样才能达到我的目标?在此先感谢,致以诚挚的问候,朱利安

4

1 回答 1

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];
于 2012-06-29T23:35:17.203 回答