问题
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:
- 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 usingDispatchQueue
is necessary, but one thing at a time. - In a separate view controller I adopted the
UITabBarControllerDelegate
protocol and settabBar?.delegate = self
. - 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