-4

I am using Swift 5. I would like to be able to programmatically detect when a tab bar item is clicked to select a different ViewController. The ideal situation would be to be able to set an IBAction event for the tab item selection. While I can establish an outlet for the tab bar item, I can't seem to find a way to set an IBAction for the item. Is there a way to do this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
bbabbitt
  • 3
  • 3

1 Answers1

0

add UITabBarControllerDelegate to your tabBarViewContriller then use this function.

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

    print("last selected index = \(lastSelectedIndex)") //show last index
    print("selected index = \(selectedIndex)") //show current selection index
}
Masoud Roosta
  • 455
  • 9
  • 19
  • This lets me know what tab item is/was selected, but I need to know when the new view is in focus. Apparently, didLoad isn't triggered when the view is switched by the tab bar. I have some housekeeping to do when a new view loads, i.e. IBAction wish. This is important (for me) when the user switches back-and-forth with the tab bar. I could use the UITabBarControllerDelegate if there was a way to trigger it. – bbabbitt Jul 28 '19 at 18:08