Bisma Saeed
Bisma Saeed

Reputation: 827

Tabbar replace view controller

I want to replace view controller from tabbar controller for some specific conditions. Here is my code.

-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{

   NSInteger selectIndex=[tabBarController.viewControllers indexOfObject:viewController];

 if (selectIndex==2) {

    UserObject * user=[[SharedClass sharedInstance] getUser];
    if (user.license_no.length>0 && user.insurance_no.length>0) {

        OfferRideVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"OfferRideVC"];

        NSMutableArray *allviews=[[NSMutableArray alloc] initWithArray:[tabBarController viewControllers]];
        [allviews removeObjectAtIndex:selectIndex];
        [allviews insertObject:vc atIndex:selectIndex];
        [tabBarController setViewControllers:allviews];

      }


  }

  return YES;
}

But my app crashes with this error. 'NSInvalidArgumentException', reason: '-[UITabBarController setSelectedViewController:] only a view controller in the tab bar controller's list of view controllers can be selected.'

Can anyone have some idea what is wrong with my code?

Upvotes: 2

Views: 1622

Answers (1)

ogres
ogres

Reputation: 3690

That happens because you are still returning YES at the end of the function, so TabBar tries to select viewController which is now not in its ViewControllers list.

Return NO from your if case,

-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{

   NSInteger selectIndex=[tabBarController.viewControllers indexOfObject:viewController];

 if (selectIndex==2) {

    UserObject * user=[[SharedClass sharedInstance] getUser];
    if (user.license_no.length>0 && user.insurance_no.length>0) {

        OfferRideVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"OfferRideVC"];

        NSMutableArray *allviews=[[NSMutableArray alloc] initWithArray:[tabBarController viewControllers]];
        [allviews removeObjectAtIndex:selectIndex];
        [allviews insertObject:vc atIndex:selectIndex];
        [tabBarController setViewControllers:allviews];

        // ViewControllers changed, return NO
        return NO;
      }


  }

  return YES;
}

Upvotes: 5

Related Questions