Search code examples
iosswiftviewcontrollers

Passing data between view controllers in Swift does not work


Would you please help me? The data (itemStr) is not passed even though the below code seems correct and I have already checked the similar questions on stack overflow.com:

1st view controller (BookTableViewController.swift):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if let SecondController = segue.destination as? BookViewController {
            SecondController.itemStr = "43"        
        }        
}

2nd view controller (BookViewController.swift):

var itemStr = String()

override func viewDidLoad() {
        super.viewDidLoad()

        itemNoLabel?.text = "BNo:" + itemStr + " GYE"       
}

When I run the program, itemStr comes as nil. I do not get "43"?

Thanks, in advance, for your kind help. Guven


Solution

  • You're running into problems because you're not really presenting the UIViewController that you think you are. You're really presenting it's UINavigationViewController.

    But you could still do something like this:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
          if let navigationViewController = segue.destination as? UINavigationController {
    
                guard let secondViewController = navigationViewController.topViewController as? BookViewController else { return }
                secondViewController.itemStr = "43"        
            }        
    }