控制UITabBar项目

时间:2018-02-06 11:57:34

标签: ios swift uitabbarcontroller uitabbaritem

我有UITabBarController我有3个视图控制器,用于使用关系segues连接的3个标签栏项目。

但我希望根据用户类型显示2 OR 3标签栏项目。例如,对于用户A,仅显示2 UITabBarItem,而对于另一用户B则显示全部3 UITabBarItem

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

在自定义标签栏实现中尝试以下方法(您必须将其设置为故事板中标签栏控制器的类):

class CustomTabBarController: UITabBarController {

    override func awakeFromNib() {
        super.awakeFromNib()

        // I have no idea how you determine your user type, so fix it according to yourself
        if user.type = "A" {
            self.viewControllers = [storyboard!.instantiateViewController(withIdentifier: "ViewController1"),
                                    storyboard!.instantiateViewController(withIdentifier: "ViewController2")]
        } else {
            self.viewControllers = [storyboard!.instantiateViewController(withIdentifier: "ViewController1"),
                                    storyboard!.instantiateViewController(withIdentifier: "ViewController2"),
                                    storyboard!.instantiateViewController(withIdentifier: "ViewController3")]
        }
    }
}

答案 1 :(得分:0)

可能的解决方案: -

  1. 以编程方式添加UITabBarItems
  2. 只需要2个UITabBarItems时以编程方式删除一个UITabBarItem
  3. 在需要时添加第三个UITabBarItem
  4. 以编程方式添加UITabBarItems: -

    UITabBarItem * itemNew = [[UITabBarItem alloc] initWithTitle:@"Page 1"
                                                         image:[UIImage imageNamed:@"page1_image_normal"]
                                                 selectedImage:[UIImage imageNamed:@"page1_image_selected"]];
    

    获取现有的tabBarItems

    NSMutableArray *tbItems = [NSMutableArray arrayWithArray:[self.tabBar items]];
    //Add your new tabBarItem
    [tbItems addObject:itemNew];
    
    //Set your tabBar items to the new array
    [self.tabBar setItems:tbItems];