问题
I have created a tab bar with 5 tabs. we want to create a feature that we can enable/disable some tabs of tab bar programmatically so that user will not able to click on it.
We have used default tab bar controller and we are using swift 3. Does anyone have an idea how to manage this stuff?
I have tried many ways but it seems that it's not possible to restrict the user to click on the tab.
Please let me know if anyone has faced and solved this issue.
回答1:
let tabBarControllerItems = self.tabBarController?.tabBar.items
if let tabArray = tabBarControllerItems {
tabBarItem1 = tabArray[0]
tabBarItem2 = tabArray[1]
tabBarItem1.isEnabled = false
tabBarItem2.isEnabled = false
}
Just put the block of code above in the viewDidLoad() method for starters and don't forget to create the tabBarItem variables
回答2:
Try this in your viewWillAppear()
method :
if let arrayOfTabBarItems = tabBarViewController.tabBar.items as! AnyObject as? NSArray,tabBarItem = arrayOfTabBarItems[2] as? UITabBarItem {
tabBarItem.enabled = false
}
Note :The above code will disable your third tab from clicking, to disable any other, just change the index in the arrayOfTabBarItems
回答3:
Swift 3 xcode 8.3.3
I am making a demo App For your Problem. This is the code for firstViewController in TabBar ViewController.
class firstViewController: UIViewController ,UITabBarControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.delegate = self
}
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if viewController.isKind(of: secondViewController.self as AnyClass) {
return true
}
if viewController.isKind(of: thirdViewController.self as AnyClass) {
return false
}
}
}
In That Demo SecondViewController is Click and open ViewController. But thirdViewController is not clicked.
回答4:
Just create a customTabBarController class and put the bellow code on viewDidLoad().
if let arrayOfTabBarItems = self.tabBar.items as AnyObject as? NSArray,let tabBarItem = arrayOfTabBarItems[3] as? UITabBarItem {
tabBarItem.isEnabled = false
}
so you can change arrayOfTabBarItems index based on your requirment.
来源:https://stackoverflow.com/questions/45318008/swift-3-tab-bar-disable-tab