Search code examples
iosswiftviewcontrollerpass-data

Passing data between a ViewController to another ViewController with navigation controller Swift 5


I hope you'll be great, the point is I wanna pass data between SeondViewController to HomeViewController and navigation controller exist between them, but unfortunately, I can't. I try present call function it's work but the simulator stuck in SecondView, and here is my views photo:

estoryboard

My secondViewController button code to pass data to homeViewcontroller is:

   @IBAction func nextStep(_ sender: Any) {
    
    let thirdVC = HomeViewController()
    thirdVC.cid = cityId
      // present(thirdVC, animated: true, completion: nil)
    }

Also, my homeViewController code that I point to it , is here:

    class HomeViewController: UIViewController {

     var txt : String = "  "
     var cid : String = "  "
    
     override func viewDidLoad() {
         super.viewDidLoad()
         // Do any additional setup after loading the view.
         print("\n iiiiiiiiiid is \(cid) ")
    }

Thanks for your attention.


Solution

  • If you are using segue, then add "segue_identifier" in storyboard and the in secondviewcontroller add:

     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
                 if segue.identifier == "segue_ identifier" {
                    let mainTab = segue.destination as! tabBarController
                    let nav = mainTab.viewControllers[0] as! UINavigationController
                    let vc = nav.viewControllers.first as! HomeViewController
                    vc.cid = cityId
                }
            }
    

    Because your segue destination is UINavigationController, you need to send data to view controller like this