iFunnyVlogger iFunnyVlogger -4 years ago 53
iOS Question

Perform Action When TabBarItem is Pressed

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!

Answer Source

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 )

}

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download