首页 > 解决方案 > How can I detect programmatically (egIBAction) when the tab selection changes views?

问题描述

我正在使用 Swift 5。我希望能够以编程方式检测何时单击选项卡栏项以选择不同的 ViewController。理想的情况是能够为选项卡项选择设置 IBAction 事件。虽然我可以为标签栏项目建立一个出口,但我似乎找不到为该项目设置 IBAction 的方法。有没有办法做到这一点?

标签: iosswiftuitabcontroller

解决方案


将 UITabBarControllerDelegate 添加到您的 tabBarViewContriller 然后使用此功能。

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {

    print("last selected index = \(lastSelectedIndex)") //show last index
    print("selected index = \(selectedIndex)") //show current selection index
}

推荐阅读