简体   繁体   中英

How to open the same VC embedded in a Navigation Controller from a TabbarController

There are 5 tabs and the first 2 of those need to open the same VC which would be embedded in a navigation controller. All of the VCs are in the storyboard. Depending on which of those 2 is tapped, I need to pass a value (I think I can figure this out) which would change some of the UI components of that VC.

What I have so far is this:

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        let indexOfTab = tabBar.items?.firstIndex(of: item)
        switch indexOfTab {
        case 1:
               // Open 1st VC with 'x' UI components
        case 2:
               // Open 1st VC with 'y' UI components
}

So I am able to open tabs 3 to 5 without any problems but the first 2 do not work properly because they are embedded in a navigation controller.

Expected result: Tapping tab index 1 followed by tab index 2 (or the other way around) should open the 2nd VC (or 1st as the case maybe) as the root view controller

Actual result: Tapping index 1 followed by tab index 2 (or the other way around) opens tab index 1 as the root view controller and pushes tab index 2.

How do I get the expected result?

EDIT: I think I know why this is happening. It is because I have segue to VC for those 2 VCs in the storyboard and then programatically I am trying to open them as well. Is there anyway to do this in a mix of storyboard and programmatic or do I need to refactor the entire tabbar programmatically?

You can create two link from the tabBarController to the VC you want present and assign to them an identifier, so in the prepareForSegue methods you can pass to the VC the value you want, this works if the two tabs present two different instance. Instead if the two tab present the same instance, you can save the instance of the VC in the prepareForSegueAction or set the child VC as delegate of the parent (I prefer the second option personally) and then you can use the method to know when a tab has been pressed and pass to the VC the value you need using the instance o the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM