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];