Byte Byte - 1 month ago 13x
Swift Question

Detecting tap on a tab in UITabBarController

I have created a tabBarController programatically like below

let tabbarController = UITabBarController()
let homeViewController = HomeViewController()
let rewardsViewController = RewardsViewController()
let moreViewController = NewMoreViewController()

let homeNVc = UINavigationController()
homeNVc.viewControllers = [homeViewController]

let rewardsNVc = UINavigationController()
rewardsNVc.viewControllers = [rewardsViewController]

let moreNVc = UINavigationController()
moreNVc.viewControllers = [moreViewController]

tabbarController.viewControllers = [homeNVc, rewardsNVc, moreNVc]

tabbarController.tabBar.items![0].title = NSLocalizedString("Dashboard", comment: "")
tabbarController.tabBar.items![1].title = NSLocalizedString("Prämien", comment: "")
tabbarController.tabBar.items![2].title = NSLocalizedString("Mehr", comment: "")
self.window?.rootViewController = tabbarController

everyThing is working . I can move through tabs perfectrly, Now I have ta tableView in my homeViewController. Which I want to reload when ever user taps on first tab of my TabBarController. Even if user is already on that viewController I want to reload tableView.

So basically How can I detect that user tapped on first ViewController ?

please guide me thanks :-)


In your homeViewController you may need to implement this delegate method:

func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

    //ask where it is first tab bar item 
    if self.tabBarController?.selectedIndex == 0 {
        // your action, e.g.:



You need to have maintained your class like this:


class YourTabBarController: UITabBarController { // inherit from UITabBarController

or this:


class YourViewController: UIViewController, UITabBarDelegate { // set protocol