Disable tab item - Swift

How to disable a specific tab item? Something like the third icon ...

self.tabBarItem.items![2].enabled = false

Should there be a way to make such a simple task as a single liner? The above does not work ...

+6
source share
6 answers

Here is the answer

if  let arrayOfTabBarItems = tabBarViewController.tabBar.items as! AnyObject as? NSArray,tabBarItem = arrayOfTabBarItems[2] as? UITabBarItem {
        tabBarItem.enabled = false
    }
+9
source

Here is my code for this using Swift 3:

    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 code block above in the method viewDidLoad()for starters and do not forget to create the variables tabBarItem, and everything is fine from there!

+7
source

tabBarItem ( ):

- UITabBarItems:

var tabBarItemONE: UITabBarItem = UITabBarItem()
var tabBarItemTWO: UITabBarItem = UITabBarItem()
etc...

viewWillAppear :

let tabBarControllerItems = self.tabBarController?.tabBar.items

if let arrayOfTabBarItems = tabBarControllerItems as! AnyObject as? NSArray{

    tabBarItemONE = arrayOfTabBarItems[0] as! UITabBarItem
    tabBarItemONE.enabled = false

    tabBarItemTWO = arrayOfTabBarItems[1] as! UITabBarItem
    tabBarItemTWO.enabled = false

}

viewWillDisappear :

override func viewWillDisappear(animated: Bool) {

    tabBarItemONE.enabled = true
    tabBarItemTWO.enabled = true

}
+3

:

Objective C viewDidLoad:.

Swift viewDidLoad(), viewWillAppear().

+1
source

To do this, I created an extension, the answer "Aditya kukntla":

 extension UIViewController {

    func enableTabbarItems(_ items: [Int]) {
        disableAllTabbarItems()
        if let arrayOfTabBarItems = tabBarController?.tabBar.items as NSArray? {
            for i in 0..<arrayOfTabBarItems.count {
                if items.contains(i) {
                    if let tabBarItem = arrayOfTabBarItems[i] as? UITabBarItem {
                        tabBarItem.isEnabled = true
                    }
                }
            }
        }
    }

    private func disableAllTabbarItems() {
        if let arrayOfTabBarItems = tabBarController?.tabBar.items as NSArray? {
            for i in 0..<arrayOfTabBarItems.count {
                if let tabBarItem = arrayOfTabBarItems[i] as? UITabBarItem {
                    tabBarItem.isEnabled = false
                }
            }
        }
    }
}
+1
source

SWIFT 4.2

if let arrayOfTabBarItems = self.tabBar.items as AnyObject as? NSArray,let 
   tabBarItem = arrayOfTabBarItems[1] as? UITabBarItem {
   tabBarItem.isEnabled = false
}
0
source

Source: https://habr.com/ru/post/1598563/


All Articles