单击 UITabBarController 的标签栏调用不同的 viewControllers

Call different viewControllers on click of tab bar of UITabBarController

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

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

以下是我打开 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

如果您想根据自定义逻辑替换所选选项卡的根视图控制器,请尝试使用 UITabBarControllersetViewControllers:animated: 方法。

你可以这样做:

- (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];
        }
    }
}

根据我的经验,有时我们不使用 tabbarVC,因为它不灵活,例如 hideshow更改项目编号。所以我们将 navigationVC 设置为 rootVC,你可以创建一个 View,只是让它看起来像一个 tabbarVC。 此视图更容易 used.And 你不需要关心任何委托方法或其他东西。你可以做任何你想做的事。 就这些了。