iFunnyVlogger
iFunnyVlogger

Reputation: 467

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!

Upvotes: 1

Views: 2577

Answers (1)

webjunkie
webjunkie

Reputation: 1184

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 )

}

}

Upvotes: 2

Related Questions