0

I have an item in my tab bar that shouldn't be enabled until certain conditions are met. I can disable that item in viewDidLoad() from my subclassed UITabBarController, but I'm having trouble creating a function that I can call when needed. Below is what I have so far - for reasons I don't understand, my tab bar item array is always nil! (Unless its initialized in viewDidLoad() where it works fine.)

func setTabState(whichTab: Int) {
    let arrayOfTabBarItems = self.tabBar.items

    if let barItems = arrayOfTabBarItems {
        if barItems.count > 0 {
            let tabBarItem = barItems[whichTab]
            tabBarItem.isEnabled = !tabBarItem.isEnabled
        }
    }
}
squarehippo10
  • 1,855
  • 1
  • 15
  • 45

2 Answers2

2

Please put below code where you want to disable tabbar item in your UITabbarController class

//Here Disable 0 Tabbar item

DispatchQueue.main.async {
    let items = self.tabBar.items!
    if items.count > 0 {
         items[0].isEnabled = false
    }
}
Rohit Makwana
  • 4,337
  • 1
  • 21
  • 29
  • This code works great from viewDidLoad but not in a function. self.tabBar.items is nil unless its called in viewDidLoad. – squarehippo10 May 31 '18 at 11:52
1

The solution turned out to be a combination of Rohit Makwana's answer and some experimentation:

  1. In viewDidLoad() of my CustomTabBarViewController I used Rohit's
    answer to set the initial state of the tab bar items. I still don't understand why using DispatchQueue is necessary, but one thing at a time.
  2. In a separate view controller I adopted the UITabBarControllerDelegate protocol and set
    tabBar?.delegate = self.
  3. Finally, I created a property observer on a variable that gets set to true when certain conditions are met:

var allButtonsPressed = false {
   didSet {
      if let items = tabBarController?.tabBar.items {
         items[1].isEnabled = allButtonsPressed
      }
   }
}

And it works! When allButtonsPressed is true, the tab bar item is instantly enabled. When it's false - disabled. Plus one to Rohit for helping me get to the solution. Now, off to learn more about DispatchQueue...

squarehippo10
  • 1,855
  • 1
  • 15
  • 45