Swift disable tab bar item with function

老子叫甜甜 提交于 2019-12-13 03:15:36

问题


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

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/50617250/swift-disable-tab-bar-item-with-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!