Detect UITabBar Selected Index/ Item Changes that is set Programmatically

JayVDiyk picture JayVDiyk · Jun 7, 2015 · Viewed 25.5k times · Source

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")
}

Answer

Eddy Liu picture Eddy Liu · Jun 8, 2015

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
    }
}