首页 > 解决方案 > 如何在 UITabBarViewController 的选项卡中显示?

问题描述

我希望能够创建一个带有一些选项卡的 TabBarViewController,然后推入给定的选项卡

let tabBarViewController = UITabBarController()
let redVc = UIViewController()
redVc.view.backgroundColor = .red

let blueVc = UIViewController()
blueVc.view.backgroundColor = .blue

tabBarViewController.viewControllers = [redVc, blueVc]

这创建了一个带有红色和蓝色选项卡的 tabBarViewController。现在我想把一个黄色的 VC 推到红色标签上,这样我就有了一个黄色和一个蓝色的标签。

let yellowVc = UIViewController()
yellowVc.view.backgroundColor = .yellow


tabBarViewController.modalPresentationStyle = .fullScreen

// this doesn't work
viewController.present(tabBarViewController, animated: true)

// must use this
tabBarViewController.viewControllers![0] = yellowVc

我应该怎么做才能在给定的选项卡中呈现?

标签: swiftuiviewcontrolleruitabbarcontroller

解决方案


您可以设置您的 UITabbarController,它的每个孩子都是 UINavigationController。

总之,您将拥有以下层次结构:

  • UITabbarController

    • 孩子1 ( UINavigationController)
      • 第一个内容 ViewController
    • 孩子2 ( UINavigationController)
      • 第二个内容ViewController

现在,在每个 contentViewController 中,您可以使用navigationcontroller.push将新的 viewController 推送到堆栈中,它将保留在选项卡栏内。


推荐阅读