Disable/Enable tabs in UITabBarController in storyboard-based app

旧街凉风 提交于 2019-12-05 12:18:54
idStar

Since you're using a Storyboard based app, I'd assume you have the UITabBarController defined in the storyboard as the root controller. Incidentally, you can also retrieve it by identifier instead of walking from the window to the root view controller.

Restricting which tabs are selectable, is achieved by setting a delegate of the UITabBarController (i.e. one that conforms to UITabBarControllerDelegate).

In the delegate, you can implement these two methods:

– tabBarController:shouldSelectViewController:

– tabBarController:didSelectViewController:

Likely, you just need the first to restrict (inhibit) selection, until your workflow is ready.

Another approach, is to set the "viewControllers' property on the tab bar controller, each time a milestone is passed. At each milestone, you set a more expansive array of view controllers into this property, which will open up the selection of the additional tab item.

SWIFT 3

(expanded for ease of understanding)

let arrayOfTabBarItems = tabBarController?.tabBar.items

        if let barItems = arrayOfTabBarItems, barItems.count > 0 {
            os_log("barItems.count is now ", barItems.count)
            tabBarItem0 = barItems[0]
            tabBarItem0.isEnabled = true
            tabBarItem1 = barItems[1]
            tabBarItem1.isEnabled = true
            tabBarItem2 = barItems[2]
            tabBarItem2.isEnabled = true
            tabBarItem3 = barItems[3]
            tabBarItem3.isEnabled = true
            tabBarItem4 = barItems[4]
            tabBarItem4.isEnabled = true
        }

This can be used in your viewWillAppear on each tab controller. Check your rules against this and restrict each tab accordingly. (more concise method)

let arrayOfAllTabBarItems = tabBarController?.viewControllers
    if   let tabBarArray = arrayOfAllTabBarItems, tabBarArray.count > 0 {
        for x in 0...tabBarArray.count-1 {
            let tabBarItem = tabBarArray[x]
            if tabBarItem.title != nil {
                if tabBarItem.title == "Tab1" || tabBarItem.title == "MyTab" || tabBarItem.title == "Tab2Check" {
                    tabBarItem.tabBarItem.isEnabled = !(isMyRuleTrue!)
                }
            }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!