Search code examples
swiftbuttonseguetabview

How to trigger a segue from a tab bar item to another by clicking a button?


I am trying to create a Tab View Item inside a Tab View Controller which switches to the other Tab View Items not only by tapping on the item in the Tab Bar but also via a button which I create myself.


Solution

  • From one of your VCs the tab bar controller, you can access the tab bar controller by accessing parent. If your VC is also embedded in a navigation controller, you need to access parent.parent.

    // assuming "self" is embedded in a navigation controller
    if let tabBarController = self.parent?.parent as? UITabBarController {
    
    }
    

    After you have the tab bar controller, you can set its selectedIndex to go to whichever tab you want:

    tabBarController.selectedIndex = 1 // second tab
    

    From the docs of selectedIndex:

    ...Setting this property changes the selected view controller to the one at the designated index in the viewControllers array...