0

我在 iOS5 的 xcode 中使用 Storyboards。我有一个带有 6 个选项卡的 TabBarController。在 TabController 之前,用户选择一种类型的帐户 A 或 B,如果选择了 B 类型,我想隐藏其中一个选项卡。

我有一个 UITabBarController 的子类,这段代码有效,但不是我想要的。

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

这使我的第二个标签变暗且无法使用,这没关系,但我真的希望它能够工作......

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

但它会导致此错误:-[UITabBarItem setHidden:]: unrecognized selector sent to instance 0x856f490 * Terminating app due to unaught exception 'NSInvalidArgumentException', reason: '-[UITabBarItem setHidden:]: unrecognized selector sent to instance 0x856f490'

还有另一种方法可以实现这一目标吗?

4

2 回答 2

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

这种方法的苹果文档说:

当您分配一组新的视图控制器运行时,标签栏控制器会在安装新视图控制器之前删除所有旧视图控制器。更改视图控制器时,选项卡栏控制器会记住先前选择的视图控制器对象并尝试重新选择它。如果选定的视图控制器不再存在,它会尝试在数组中与先前选择相同的索引处选择视图控制器。如果该索引无效,它将选择索引 0 处的视图控制器。

关于您的错误消息:您收到该错误是因为 tabBar 没有实现 method setHidden:

于 2012-06-12T12:38:17.887 回答
1

d.ennis 的回答为我指明了正确的方向。必须使用 Storyboards 为 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];
于 2012-06-21T20:54:58.717 回答