检测点击 UITabBarController 中的选项卡

Detecting tap on a tab in UITabBarController

我已经像下面这样以编程方式创建了一个 tabBarController

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
}

一切正常。我可以完美地浏览选项卡,现在我家里有一个 tableViewViewController。当用户点击我的 TabBarController 的第一个选项卡时,我想重新加载。即使用户已经在 viewController 上,我也想重新加载 tableView。

所以基本上我如何检测第一个点击的用户 ViewController?

请指导我谢谢:-)

调用UITabBarControllerDelegate并实现该方法

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

}

在您的 homeViewController 中,您可能需要实现此委托方法:

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()
    }

}

注意:

您需要像这样维护您的 class:

a)

class YourTabBarController: UITabBarController { // inherit from UITabBarController

或者这个:

b)

class YourViewController: UIViewController, UITabBarDelegate { // set protocol

只需实现以下委托方法,

func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {

        if item.title == "first tab name"{
            //Do your thing
    }

我最近写过类似的东西。为了保持一致性,我为我使用的每个选项卡创建了一个基础 class BaseTabBarViewController。但请注意,如果选项卡是导航控制器,则从 BaseTabBarViewController 继承的是根视图控制器。 这个基础 class 实现了 UITabBarControllerDelegate 协议。在 viewDidLoad 中,我们将其标记为委托。 在委托方法中(Objective-c,在swift 3中非常相似):

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {


if (tabBarController.selected == 0)
{
   // do what you need

要访问哪个 tabBarItem 被点击,请在自定义 class 中为 UITabBarController

重写以下函数

Swift:

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
   guard let index = tabBar.items?.index(of: item) else { return }

   // Do something with the index
}