Search code examples
iosuitabbarcontrolleruitabbaruitabbaritem

How to check if a TabBar item is already present before adding at run time?


I have a tab bar project with one tab in the beginning and the view controller has buttons. If a button is tapped - a specific view controller is expected to be added to the tabbarcontroller/tab items. But each time I press the button the same viewcontroller/tab item is being added (multiple tab items of the same). I am trying to limit one tab item for one Viewcontroller, regardless how many times the button is tapped. Any help would be appreciated.

 -(IBAction) buttontap:id(sender){
UITableViewController*TableView = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Table A"];
       TableView.title = @"Table A";

 NSMutableArray *TabBarItems = [NSMutableArray arrayWithArray:self.tabBarController.viewControllers];


if ([self.tabBarController.tabBarItem.title.description isEqualToString:@"Table A"])
    {
  [TabBarItems addObject:nil];

  }
 else
  {
  [TabBarItems addObject:TableView];
    TableView.tabBarItem.image = [UIImage imageNamed:@"contents.png"];

 }
    [self.tabBarController setViewControllers:TabBarItems];

 }

Solution

  • you could declare Tableview in your header file like so:

    UITableViewController *TableView;
    

    Now you can check if the Viewcontroller already exists:

    if(!TableView){
        //your code here
        //instantiate TableView ad add it to the TabBar.
    
    }
    

    That way, it will only be executed on the first buttonTap.

    EDIT:

    Of course this wold require you to declare a ViewController for every button you have. A more dynamic approach would be to use that mutable Array you create and compare each of the items to the newly created viewController using -(BOOL)isEqual::

    UITableViewController*TableView = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Table A"];
    NSMutableArray *TabBarItems = [NSMutableArray arrayWithArray:self.tabBarController.viewControllers];
    BOOL found = NO;
    for (UIViewController *vc in TabBarItems){
        if([vc isEqual:TableView]){
             found=YES;
        }
    }
    if(!found){
        [TabBarItems addObject:TableView];
         TableView.tabBarItem.image = [UIImage imageNamed:@"contents.png"];
        [self.tabBarController setViewControllers:TabBarItems];
    
    }
    

    Now you can add more buttons without adding more variables to your header. Have fun.