如何将 ViewController 添加到 UITabBarController 并以编程方式加载它?

How do I add a ViewController to a UITabBarController and load it Programmatically?

我正在尝试将自定义 viewController 放入 UITabBarController,然后呈现它。但是当我尝试下面的内容时,我得到的是一个空白屏幕,底部有一个空白标签栏。

@IBAction func didOpenTabs(_ sender: Any) {
    let tabBarController = UITabBarController()

    let vc = ViewController()

    let controllers = [vc]

    tabBarController.viewControllers = controllers

    self.present(tabBarController, animated: true, completion: nil)

}

我需要访问视图控制器,因为视图控制器需要从变量加载数据,并在关闭时将数据保存到同一个变量。

我觉得我在基本层面上做错了什么,但对 swift 不够熟悉,无法确定它是什么。

问题是你不能在 viewDidLoad 调用之前分配 viewControllers,因为内部 UITabBar 还没有初始化,因此要解决这个问题你可以子类化您的 UITabBarController 以确保您在正确的位置设置那些 viewControllers (viewDidLoad),最终您的代码可能是:

import UIKit

class MyTabBarController:UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let vc1 = UIViewController()
        vc1.view.backgroundColor = UIColor.green
        vc1.tabBarItem = UITabBarItem(tabBarSystemItem: .bookmarks, tag: 0)

        let vc2 = UIViewController()
        vc2.view.backgroundColor = UIColor.red
        vc2.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag: 1)

        viewControllers = [vc1, vc2]
    }
}

class ViewController: UIViewController {
    @IBAction func showTabVc() {
        self.present(MyTabBarController(), animated: true, completion: nil)
    }
}