Search code examples
iosswiftstoryboardtabbar

Is it possible to navigate from a tab bar controller to another tab bar controller?


I have an app with three tabs as the root navigation, and there's a table view in the first tab. So when a user clicks on a table cell user should navigate to another View which contains two tabs. How do I achieve this?

Current Storyboard

enter image description here

This is what I have so far. I'm still learning ios development and I want to know if this is possible


Solution

  • Remove the storyboard segue from the table view to the second tab bar controller. And present the second tab bar controller from the table view controller's didSelectRowAt method. And you can pass data to the embedded view controllers like this

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let secondTabBarController = self.storyboard?.instantiateViewController(withIdentifier: "SecondTabBarController") as?  SecondTabBarController {
            if let navControllers = secondTabBarController.viewControllers as? [UINavigationController] {
                if let fourthVC = navControllers.first(where: { $0.topViewController is FourthVC })?.topViewController as? FourthVC {
                    fourthVC.name = "name"
                }
                if let fifthVCvc = navControllers.first(where: { $0.topViewController is FifthVC })?.topViewController as? FifthVC {
                    fifthVCvc.id = 20
                }
            }
            self.present(secondTabBarController, animated: true, completion: nil)
        }
    }
    

    Replace the class names and storyboard identifiers with proper class names and identifiers

    class FourthVC: UIViewController {
        var name: String?
        override func viewDidLoad() {
            super.viewDidLoad()
            print(name)
        }
    }
    class FifthVC: UIViewController {
        var id: Int?
        override func viewDidLoad() {
            super.viewDidLoad()
            print(id)
        }
    }