2012-06-11 75 views
0

我在xcode中使用Storyboard與iOS5。我有一個帶有6個選項卡的TabBarController。在TabController之前,用戶選擇一種類型的帳戶A或B,如果選擇了類型B,我想隱藏其中一個選項卡。iOS5 setHidden UITabBarItem導致崩潰

我有一個UITabBarController的子類和這段代碼的作品,但它不完全是我想要的。

if (accountType == 2) { 
    [[[[self tabBar] items] objectAtIndex:1] setEnabled:NO]; 
} 

這使我的第二個選項卡暗,無法使用這是確定的,但我真的希望這個工作......

[[[[self tabBar] items] objectAtIndex:1] setHidden:YES]; 

但它會導致這個錯誤: - [UITabBarItem setHidden:]:無法識別選擇發送到實例0x856f490 *終止應用程序由於未捕獲的異常 'NSInvalidArgumentException',原因: ' - [UITabBarItem setHidden:]:無法識別的選擇發送到實例0x856f490'

是否有另一種方法來實現這一點?

回答

1

爲什麼不等待tabBar viewControllers的初始化,直到您知道用戶選擇哪種類型的帳戶?爲此,使用例如setViewControllers:animated:的方法。如下:

if (accountType == 1) { 
    NSArray* controllersForTabBar = [NSArray arrayWithObjects:myVC1,myVC2,myVC3,myVC4,myVC5,myVC6 nil]; 
    [[[self tabBar] setViewControllers:controllersForTabBar] animated:YES]; 
} 
if (accountType == 2) { 
    NSArray* controllersForTabBar = [NSArray arrayWithObjects:myVC1,myVC2,myVC3,myVC4,myVC5, nil]; 
    [[[self tabBar] setViewControllers:controllersForTabBar] animated:YES]; 
} 

蘋果文檔這種方法說:

When you assign a new set of view controllers runtime, the tab bar controller removes all of the old view controllers before installing the new ones. When changing the view controllers, the tab bar controller remembers the view controller object that was previously selected and attempts to reselect it. If the selected view controller is no longer present, it attempts to select the view controller at the same index in the array as the previous selection. If that index is invalid, it selects the view controller at index 0.

關於你的錯誤消息:由於使用TabBar沒有實現的方法setHidden:你得到這個錯誤。

1

d.ennis答案指出我正確的方向。需要稍微調整它與iOS5的故事板...

// load the storyboard by name 
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; 

if (accountType == 1) { 
    UIViewController *fvc = [storyboard instantiateViewControllerWithIdentifier:@"First"]; 
    UIViewController *svc = [storyboard instantiateViewControllerWithIdentifier:@"Second"]; 
} else { 
    UIViewController *fvc = [storyboard instantiateViewControllerWithIdentifier:@"First"]; 
    UIViewController *svc = [storyboard instantiateViewControllerWithIdentifier:@"Second"]; 
    UIViewController *tvc = [storyboard instantiateViewControllerWithIdentifier:@"Third"]; 

}  

tabBarController = [[UITabBarController alloc] init]; 
tabBarController.delegate = self; 

NSArray *controllersForTabBar = [NSArray arrayWithObjects: fvc, svc, nil]; 

[tabBarController setViewControllers:controllersForTabBar animated:NO]; 

[self.view addSubview:tabBarController.view]; 
+0

我認識的代碼是不是100%,但寫你的想法:) – Andy