1

How do I add an action to a Tab Bar Item when it is pressed. I've tried a few things, but either they aren't right, or I'm putting them in the right location.

In my storyboard, I have a tab view controller, which is connected to a navigation controller, and that is of course connected to a ViewController. I've tried using

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

I added UITabBarDelegate, and it sill doesn't work? Any ideas? Thanks!

iFunnyVlogger
  • 437
  • 1
  • 6
  • 17

1 Answers1

2

You need to create a custom tab controller file and assign it as a custom class to your tab controller. Here's an example:

import UIKit

class CustomTabViewController: UITabBarController,UITabBarControllerDelegate {

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    print("Selected item", item.tag )
}


func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    print("Selected view controller", viewController)
    print("index", tabBarController.selectedIndex )

}

}
webjunkie
  • 1,184
  • 9
  • 19