首页 > 解决方案 > 点击UITabBarController的标签栏调用不同的viewControllers

问题描述

下面是我UITabBarController在故事板中的结构图像。

在此处输入图像描述

现在在情节提要中,AboutUsViewController(UIViewController)与我的 tabBar 按钮单击事件绑定,即如果我单击 tabBar 按钮,AboutUsViewController则正在打开,但现在我的功能基于某些条件。我想打电话ContactRequstViewController而不是AboutUsViewController在同一个 tabBar 按钮上单击。

以下是我打开的代码ContactRequstViewController

-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
      if (tabBarController.selectedIndex == 2){
           UIStoryboard *story =  [UIStoryboard storyboardWithName:@"iPhone" bundle:nil];
           ContactRequstViewController *contactVC = [story instantiateViewControllerWithIdentifier:@"ContactUsView"];
          [self.navigationController pushViewController:contactVC animated:YES];
      }
}

写完上面的代码后,我无法加载ContactRequestViewController.

标签: iosobjective-cuitabbarcontrolleruitabbar

解决方案


如果要根据自定义逻辑替换所选选项卡上的根视图控制器,请尝试setViewControllers:animated:使用UITabBarController.

你可以这样做:

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    if (tabBarController.selectedIndex == 1 && tabBarController.viewControllers.count > tabBarController.selectedIndex) {
        BOOL shouldShowContactVC = (BOOL)(rand() % 2);
        NSMutableArray *viewControllers = [[tabBarController viewControllers] mutableCopy];
        UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UIViewController *newVC = nil;
        if (shouldShowContactVC) {
            newVC = [main instantiateViewControllerWithIdentifier:@"ContactUsVC"];
        } else {
            newVC = [main instantiateViewControllerWithIdentifier:@"AboutUsVC"];
        }
        if (newVC) {
            [viewControllers replaceObjectAtIndex:tabBarController.selectedIndex withObject:newVC];
            newVC.tabBarItem = viewController.tabBarItem;
            [tabBarController setViewControllers:viewControllers animated:YES];
        }
    }
}

推荐阅读