iosuitabbarcontrolleruitabbaruitabbaritem

Detect UITabBar Selected Index/ Item Changes that is set Programmatically


I would like to know how do we detect when the selected TabBar Item or Index is changed when the changes is done programmatically?

self.tabBarController.selectedIndex = 1;

This two delegate function only detect changes when the tabBar Item was selected by user. It does not fire when the changes to the selectedIndex was done programmatically.

func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
    println("tabBarController didSelectViewController")
}

override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!) {
    println("tabBar didSelectItem")
}

Solution

  • Previous answers are sufficient to "detect" the changes, however it does not detect which index is being pressed.

    func selectItemWithIndex(value: Int) {
        self.tabBarControllertabBarController.selectedIndex = value;
        self.tabBar(self.tabBar, didSelectItem: (self.tabBar.items as! [UITabBarItem])[value]);
    }
    

    self.selectedIndex will not return the selected index right away. To check which item is being pressed, we would need to compare the item with the tabBarItems in our UITabBarController

    override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!) {
        if item == (self.tabBar.items as! [UITabBarItem])[0]{ 
           //Do something if index is 0
        }
        else if item == (self.tabBar.items as! [UITabBarItem])[1]{
           //Do something if index is 1
        }
    }