Swift: How to execute an action when UITabBarItem is pressed

K Swisha picture K Swisha · Jun 15, 2015 · Viewed 45.8k times · Source

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.

Answer

Nikita Zernov picture Nikita Zernov · Jun 15, 2015

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.