标签栏替换视图控制器

bis*_*sma 2 objective-c ios7

我想在某些特定条件下从 tabbar 控制器替换视图控制器。这是我的代码。

-(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;
}
Run Code Online (Sandbox Code Playgroud)

但是我的应用程序因此错误而崩溃。'NSInvalidArgumentException',原因:'-[UITabBarController setSelectedViewController:] 只能选择标签栏控制器的视图控制器列表中的视图控制器。

任何人都可以知道我的代码有什么问题吗?

ogr*_*res 5

发生这种情况是因为您在函数结束时仍然返回YES,因此 TabBar 尝试选择现在不在其 ViewControllers 列表中的 viewController。

从你的 if case返回NO,

-(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;
}
Run Code Online (Sandbox Code Playgroud)