UITabBarController 没有正确初始化选项卡视图控制器

UITabBarController doesn't properly initialize tab view controllers

我正在以编程方式创建 UITabbarController 及其所有选项卡的内容,如下所示:

private func createTabBarController()
{
    /* Only create tabBarController once! */
    if (RootRouter._tabBarController == nil)
    {
        let firstPageViewController = FirstPageViewController(nibName: "FirstPageViewController", bundle: nil)
        let secondPageViewController = SecondPageViewController(nibName: "SecondPageViewController", bundle: nil)
        let thirdPageViewController = ThirdPageViewController(nibName: "ThirdPageViewController", bundle: nil)
        let thirdPageNavigationController = ThirdPageNavigationController(rootViewController: thirdPageViewController)
        let fourthPageViewController = FourthPageViewController(nibName: "FourthPageViewController", bundle: nil)

        thirdPageViewController.loadViewIfNeeded()

        RootRouter._tabBarController = UITabBarController()
        RootRouter._tabBarController?.viewControllers =
        [
            firstPageViewController,
            secondPageViewController,
            thirdPageNavigationController,
            fourthPageViewController
        ]

        /* This shouldn't be necessary! */
        let tabCount = RootRouter._tabBarController!.viewControllers?.count ?? 0
        for i in 0 ..< tabCount
        {
            RootRouter._tabBarController?.selectedIndex = i
        }
    }
}

如果我注释掉此方法的最后一部分,应用程序启动时将无法正确初始化选项卡:仅显示前三个选项卡按钮,其中 none 突出显示。

如果启用了最后一个代码部分,它将正常工作并且看起来是正确的,但是该方法似乎是一种 hack,我认为以后可能会产生副作用。我是否缺少正确初始化所有选项卡(和选项卡按钮)的任何内容?

selectedIndex

This property nominally represents an index into the array of the viewControllers property. However, if the selected view controller is currently the More navigation controller, this property contains the value NSNotFound

您必须 select 任何索引一次。

而不是这样做

 let tabCount = RootRouter._tabBarController!.viewControllers?.count ?? 0
 for i in 0 ..< tabCount
    {
            RootRouter._tabBarController?.selectedIndex = i
    }

这样做:

 RootRouter._tabBarController?.selectedIndex = 0 // Any other index

您的方法没有任何问题,但不需要 RootRouter._tabBarController?.selectedIndex 的迭代调用。