tabBarController didSelect does not get called

Viewed 2985

I am having a problem with

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

delegate firing. The problem lies when I try to use self.tabBarController?.selectedIndex and change a tab programmatically. Once I use selectedIndex and go back to a previous tab and click on the tabBarItem the delegate does not fire anymore. Delegate only fires if I do not use selectedIndex but once i use it the didSelect delegate never fires again even if I tap on the tabBar item. Any suggestions? Thanks for your help!

3 Answers

You need to call delegate programmatically like below For eg. I need to select SettingsTab which is at 4th index, i can achieve using this code. Here didSelect is also called programmatically

if let tabbarC = self.tabBarController{
        tabbarC.selectedIndex = 4
        let setting = tabbarC.viewControllers![4]
        self.tabBarController(tabbarC, didSelect: setting)

}

Hope this helps!

Tabbar delegate is called only in response to user taps in the tab bar and is not called when your code changes the tab bar contents programmatically.

Anyone who had the issue with UITabBarController delegate with Hero. the problem is with Hero transition delegate and solution is to put your tabBarController in a ViewController as a container. Then setup Hero on the container and problem solves.

tabBarController.viewControllers = [...]
let container = UIViewController()
container.addChild(tabBarController)
container.view.addSubview(tabBarController.view)
tabBarController.didMove(toParent: container)
tabBarController.view.frame = CGRect(x: 0, y: 0, width: container.view.frame.width, height: container.view.frame.height)
container.modalPresentationStyle = .fullScreen
container.hero.isEnabled = true
container.modalAnimationType = .slide(direction: .left)
rootViewController.present(container, animated: true, completion: nil)
Related