1
votes

I can swap from one UIViewController to another within a UITabBarController using tabBarController?.selectedIndex = targetIndex. I would like to know how to trigger a segue after the switch.

I have tried doing if let vc = tabBarController?.viewControllers?[0] as MyViewController {} and calling vc.performSegue() but it errors out, complaining that it's a UINavigationController. (I couldn't even get vc.prepare() to work but I can't work out how to create a UIStoryBoardSegue, which it requires as the first argument, from scratch using the segue identifier.) I think this is because all of my UIViewControllers in the UITabBarController are within Navigation Controllers.

How do I switch from index 0 to 1 in the tab bar controller, and then trigger a segue in the view controller embedded in the navigation controller? Note, I need to pass in a copy of the calling object (my UIViewController) or a payload for contextual purposes to the UIViewController being segued to.

1

1 Answers

1
votes

Well like you said the viewController which is presented at the index is a UINavigationController. You should get the rootViewController of the UINavigationController and perform the Segue on the RootViewController.

Below code should work:

 self.tabBarController?.selectedIndex = 1
 guard let vc = self.tabBarController?.viewControllers?[1] as? UINavigationController else {
     return
 }
 guard let rootVC = vc.viewControllers.first as? SecondViewController else {
     return
 }
 rootVC.vc = self
 rootVC.performSegue(withIdentifier: "test", sender: self)