Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :-)

like image 686
Byte Avatar asked Sep 12 '25 18:09

Byte


2 Answers

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.:
        self.tableView.reloadData()
    }

}

NOTE:

You need to have maintained your class like this:

a)

class YourTabBarController: UITabBarController { // inherit from UITabBarController

or this:

b)

class YourViewController: UIViewController, UITabBarDelegate { // set protocol
like image 93
pedrouan Avatar answered Sep 14 '25 09:09

pedrouan


Invoke UITabBarControllerDelegate and implement this method

func tabBarController(tabBarController: UITabBarController,   didSelectViewController viewController: UIViewController){

}
like image 42
Sofeda Avatar answered Sep 14 '25 09:09

Sofeda