Home > OS >  How to pass data from First TabBarItem to Second TabBarItem
How to pass data from First TabBarItem to Second TabBarItem

Time:12-09

enter image description here

Above I have a TabBarController with 4 buttons. When I press the second TabBarItem(Cars) or third TabBarItem(Bicycles) I want to pass some values from the firstTabBarItem(HomeScreen) . I'm using Swift 5 and I don't have a SceneDelegate in my main project (is a 3 years old project), I have only the AppDelegate and this is why I wasn't able to try the only example which I found from Stackoverflow about a similar question like mine. I managed somehow to pass the data between ViewControllers through TabBarController but I don't think is the right approach anymore (as some people from this community are also saying this on some threads) because when I click on different TabBarItems the data get lost and after is showing up again but with the wrong values etc. I will attach below a GIF with the bugs which I'm getting while I navigate and also my current code with a link to the DEMO project on GitHub (enter image description here

Thank you for reading this !

CodePudding user response:

The reason is that viewWillAppear of PostcodeViewController is called before the selectedIndex of your tabbar is changed. The first time it works ok. Just put the line:

print("selected index = \(self.tabBarController?.selectedIndex ?? -1)")

in your viewWillAppear and you will see.

The easiest way to fix your code is to move the logic of PostcodeViewController from viewWillAppear to viewDidAppear.

CodePudding user response:

a simple workaround can be.. store data in a static variable in login class, you can access it in other classes.

long workaround is,

create a Custom TabBar programmatically, pass data from login viewController to parent CustomTab bar, and pass data to next screen with the help of delegates.

CodePudding user response:

The fix was to move the code of PostcodeViewController from viewWillAppear to viewDidAppear like this:

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        print("Selected index: \(self.tabBarController?.selectedIndex ?? -1)")
        
        if self.tabBarController?.selectedIndex == 1 {
            receivedValueLabel.text = "Value received for Cars: \n"   receivedValueFromHomeScreen
        }

        if self.tabBarController?.selectedIndex == 2 {
            receivedValueLabel.text = "Value received for Bicycles: \n"   receivedValueFromHomeScreen
        }
    }

Now everything works perfect !

GIF below:

enter image description here

  • Related