2016-03-04 140 views
2

我想替換視圖控制器從TabBar控制器的一些特定的條件。這是我的代碼。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; 
} 

但我的應用程序崩潰與此錯誤。 'NSInvalidArgumentException',原因:' - [UITabBarController setSelectedViewController:]只能選擇標籤欄控制器視圖控制器列表中的視圖控制器。'

任何人都可以有一些想法我的代碼有什麼問題嗎?

回答

4

發生這種情況的原因是,您仍然在函數的末尾返回YES,所以TabBar會嘗試選擇viewController,它現在不在其ViewControllers列表中。

從您的情況,如果返回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; 
} 
+0

是的,我確實在didSelectViewController代表同樣的事情,它工作正常。謝謝。 – bisma

相關問題