iosswiftuitabbarcontrollerreswift

UITabBarController doesn't properly initialize tab view controllers


I'm creating a UITabbarController and all its tab's contents programmatically, like so:

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
        }
    }
}

If I comment-out the last part in this method the tabs won't be initialized properly on app start: Only the first three tab buttons are displayed and none of them are highlighted.

If the last code part is enabled it will work and look correct however the approach seems like a hack and I think might lead to side effects later. Is there anything I'm missing to initialize all tabs (and tab buttons) correctly?


Solution

  • 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

    You have to select any index once.

    Instead of doing this

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

    Do like that:

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

    There is nothing wrong in your approach, But the iterative call of RootRouter._tabBarController?.selectedIndex not required.