【问题标题】:iOS5 setHidden UITabBarItem causing crashiOS5 setHidden UITabBarItem 导致崩溃
【发布时间】:2012-06-22 04:54:58
【问题描述】:

我在 iOS5 的 xcode 中使用 Storyboard。我有一个带有 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 * 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[UITabBarItem setHidden:]:无法识别的选择器发送到实例 0x856f490”

还有其他方法可以实现吗?

【问题讨论】:

    标签: ios5 storyboard uitabbaritem


    【解决方案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 没有实现方法 setHidden:

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-23
        • 2020-12-02
        • 2013-11-11
        • 2011-01-24
        • 2015-02-23
        • 2011-04-23
        相关资源
        最近更新 更多