Swift: How to execute an action when UITabBarItem is pressed

Currently I have a Tab Bar Controller that is connected to a tableview controller. I'm trying to go to the top of the tableview when I press the tab bar item. I know how to get to the top of the tableview. I just don't know how to do an action when the item is pressed.


You should use UITabBarDelegate with method didSelectItem. Use it as any standard delegate:

class yourclass: UIViewController, UITabBarDelegate {
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        //This method will be called when user changes tab.
    }
}

And do not forget to set your tab bar delegate to self in view controller.


Here is an answer to this question

Basically you do this:

  • Make sure your view controller is subscribed to the UITabBarDelegate
  • Set tags in IB for each tab bar item
  • Implement the didSelectItem method, something like this:

    -(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
        if(item.tag == 1) {
           // Code for item 1
        }
        else if(item.tag == 2) {
           // Code for item 2
        }
    }
    

This will give you access to each tab item tapped event. Hope it helps!

In Swift:

func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    if(item.tag == 1) {
        // Code for item 1
    } else if(item.tag == 2) {
        // Code for item 2
    }
}