如何从单个UITabBar项目中有条件地选择UIViewController并保持TabBar可见



关于S/O的第一个问题,如果我没有遵守任何协议,请道歉。我一直在尝试使用同一UITabBar项目中的4个UIViewControllers有条件地显示4种不同类型的场景。它必须是TabBar上的同一项,因为使用的UIViewController依赖于数据而不是用户选择。

我知道不建议对UITabBarController进行子类化,所以我设置了一个UIViewController来处理所需场景的条件选择(请参阅下面的代码)。这很好,但尽管我尝试了我能想到的一切,但未能在新选择的视图底部显示TabBar。我也尝试过使用UINavigation控制器,但不太成功。在Storyboard中,我尝试了设置视图大小和演示样式的所有不同排列,在模拟指标中将底部栏更改为选项卡栏,并尝试使用Segues。没有一个产生必要的结果。

- (void)viewDidLoad
{
[super viewDidLoad];
int m = 1;
UIViewController *viewController;
if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12 ) {
viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"M31TVC"];
}else if (m == 4 || m == 6 || m == 9 || m == 11 ){
viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"M30TVC"];
}else if (m == 13 ){
viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"M29TVC"];
}else if (m == 2 ){
viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"M28TVC"];
}else {
// error code here
}
viewController.hidesBottomBarWhenPushed = NO;
[self presentViewController:viewController animated:NO completion:nil];

}

提前感谢任何知道如何做这件事的人。

与其尝试替换将显示给用户的控制器,不如只替换其视图。这意味着您应该实现容器视图控制器:

  • 创建UITabBarController并使其中一个项成为UIViewController
  • 将其制作成一个自定义控制器,并添加以下属性。

    @property (nonatomic, strong) IBOutlet UIView *currentView
    @property (nonatomic, strong) UIViewController *currentViewController
    
  • 将UIView添加到情节提要中的控制器,并将其连接到*currentView出口。

现在,每当用户在您的应用程序中达到这一点时,您都要执行以下操作:

UIViewController *viewController;
if (month == 1 || 3 || 5 || 7 || 8 || 10 || 12 ) {
viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"M31TVC"];
}else if (month == 4 || 6 || 9 || 11 ){
viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"M30TVC"];
}else if (month == 13 ){
viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"M29TVC"];
}else if (month == 2 ){
viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"M28TVC"];
}else {
// error code here
}
[self addChildViewController:viewController];
[viewController didMoveToParentViewController:self];
if (self.currentViewController){
[self.currentViewController willMoveToParentViewController:nil];
[self transitionFromViewController:self.currentViewController toViewController:viewController duration:0 options:UIViewAnimationOptionTransitionNone animations:^{
[self.currentViewController.view removeFromSuperview];
[self.currentView addSubview:viewController.view];
} completion:^(BOOL finished) {
[self.currentViewController removeFromParentViewController];
self.currentViewController = viewController;
}];
} else {
[self.currentView addSubview:viewController.view];
self.currentViewController = viewController;
}

这就是我在应用程序上创建自定义选项卡控制器的方法,而不是使用默认的UITabBarController。

最新更新