【问题标题】:How do I add a ViewController to a UITabBarController and load it Programmatically?如何将 ViewController 添加到 UITabBarController 并以编程方式加载它?
【发布时间】:2018-01-26 02:58:03
【问题描述】:

我正在尝试将自定义 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 不够熟悉,无法确定它是什么。

【问题讨论】:

    标签: swift uitabbarcontroller viewcontroller


    【解决方案1】:

    问题是您不能在调用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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 2018-05-08
      • 2011-08-22
      • 2014-11-25
      • 2016-12-01
      相关资源
      最近更新 更多