dean
dean

Reputation: 331

How to disable selection of tab bar items - swift

I have an application that has two UIViewcontroller embedded in a UITabBarcontroller. When I am in UIViewController-1, i would like to press a button that disables all item selection of the tab bar. My effort is below but I am not sure how to complete the code ...

enter image description here

When I am in the 'Folders' UIViewController I would like to disable the selection of any tab bar item:

 class Folders: UIViewController, UITableViewDataSource, UITableViewDelegate{

 ...
 // DISABLE TAB BAR ITEMS
 func disable (){
    let tabBarItemsArray = self.tabBarController?.tabBar.items
    tabBarItemsArray[0].enabled = false // THIS BIT OF CODE IS NOT RECOGNIZED BY XCODE
  }
 ...
 }

Upvotes: 0

Views: 3875

Answers (3)

Sudhir
Sudhir

Reputation: 1

if you want to disable one tabbar item at once then this is for disabling the first one:

guard let tabbars = self.tabBar.items else {
                  return
              }
              tabbars[0].isEnabled = false

but if you want them all to be disabled at once then this is the one to be implemented:

 self.tabBar.items?.map{$0.isEnabled = false}

Upvotes: 0

Ayaz Rafai
Ayaz Rafai

Reputation: 281

You can do that using single line of code. Please check following code.

You can execute this from any controller.

self.navigationController?.tabBarController?.tabBar.items![0].isEnabled = false

Another way

You can define NotificationCenter observer to achieve. Please check following code. *In TabBar Controller file.

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    NotificationCenter.default.addObserver(self, selector: #selector(disableTab(notification:)), name: Notification.Name("disableTab"), object: nil)
}

@objc func disableTab(notification: Notification) {
    self.TabBarItem.isEnabled = false
}

Fire from anywhere as following...

NotificationCenter.default.post(name: Notification.Name("disableTab"), object: nil)

Upvotes: 0

ielyamani
ielyamani

Reputation: 18581

tabBarItemsArray is optional, its type is [UITabBarItem]?.

You could initially force unwrap it: tabBarItemsArray![0], but the right way is to use if let construct:

if let tabBarItemsArray = tabBarController.tabBar.items {
    tabBarItemsArray[0].isEnabled = false
}

or:

guard let tabBarItemsArray = tabBarController.tabBar.items else {
    fatalError("Error")
}
let item = tabBarItemsArray[0]
item.isEnabled = false

Upvotes: 4

Related Questions