在 ViewController Swift 中添加 UITabBar 3(不实现 UITabBarController)

Add UITabBar in ViewController Swift 3(NOT TO IMPLEMENT UITabBarController)

我成功地将 UITabBar 添加到我的 UIViewController。但是,当标签被选中时,我无法切换视图控制器。我使用了以下方法:

public func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

    switch item.tag {
    case 1 :
          var storyboard = UIStoryboard(name: "Main", bundle: nil)
            let viewController = storyboard.instantiateViewController(withIdentifier: "HardwareViewController") as! HardwareViewController
            self.addChildViewController(viewController)
        break
    case 2 :

 self.performSegue(withIdentifier : IDENTIFIER_SEGUE_SYSTEMVC, sender : nil)
        break
    case 3 :

        var storyboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "SystemViewController") as! SystemViewController
        self.view.insertSubview(viewController.view!, belowSubview: self.tabBar)
        break
    case 4 :

        var storyboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "HardwareViewController") as! HardwareViewController
      self.view.insertSubview(viewController.view!, belowSubview: self.tabBar)
        break
    case 5 :

        var storyboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier : "SystemViewController") as! SystemViewController
       self.view.insertSubview(viewController.view!, belowSubview: self.tabBar)
        break
    default:
        break
    }
}

但是,其中 none 个有效。 Segue 提供了一个新的 ViewController 和 tabbar hides.It 将控件一起带到了一个新的 viewcontroller。 我有两个疑问:

  1. 当各个标签栏被标记时,如何在同一视图中显示各个 viewcontroller?
  2. 如何使用显示有初始视图控制器的标签栏加载视图控制器?假设加载带有选项卡栏的视图控制器时,还应显示要显示在第一个选项卡上的视图控制器。

您正在尝试的功能public func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem)是所选项目的标签栏委托方法,您不能使用它来设置标签栏控制器。

在加载到内存之前,您应该为标签栏控制器提供视图控制器。

试试看:

let viewController1 = storyboard.instantiateViewController(withIdentifier: "HardwareViewController") as? HardwareViewController
    let viewController2 = storyboard.instantiateViewController(withIdentifier: "SystemViewController") as! SystemViewController
    let viewController3 = storyboard.instantiateViewController(withIdentifier: "HardwareViewController") as! HardwareViewController
    let viewController4 = storyboard.instantiateViewController(withIdentifier : "SystemViewController") as! SystemViewController
    let viewController3 = storyboard.instantiateViewController(withIdentifier: "HardwareViewController") as! HardwareViewController

    var tabbarControllers = [viewController1, viewController2, viewController3, viewController4, viewController5]

   yourtabbarController.viewControllers = tabbarControllers
   // Now load your tabbar controller

UITabbarController

完成有关 UITabbarController by Apple. And here is details about viewControllers 属性 的基本教程