How to pass data from container view controller to other controllers by segue?

134 Views Asked by At

enter image description here

I want to update the label in rightmost controller by entering text from my container view controller (and click button to submit the text) but the label does not get updated. I am not sure which part of my code is wrong. And, are there any good solutions to share data between container and its parent? Thx.

code below:

import UIKit

class ChildViewController: UIViewController {

    override func viewDidLoad() {
    super.viewDidLoad()

}


@IBOutlet weak var TextField: UITextField!


@IBAction func PassItToUpdate(_ sender: UIButton) {
    let parentController = self.parent as! MainViewController
    parentController.performSegue(withIdentifier: "PassToUpdate", sender: parentController)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "PassToUpdate" {
        let vc = segue.destination as! UpdateViewController
        vc.UpdateTextLabel.text = TextField.text
    }
}

}



import UIKit

class MainViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

    }

}


import UIKit

class UpdateViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()

}

@IBOutlet weak var UpdateTextLabel: UILabel!


}
1

There are 1 best solutions below

3
On

For future reference, it doesn't work is usually not enough info for us to help you, you should mention if you get an error (which one), if it crashes (what does the console say), if nothing happens, etc.

I'm going to go ahead and guess that your app is crashing because you're accessing UpdateTextLabel before the view, so the text field hasn't been created.

Make this change to your prepareForSegue function:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "PassToUpdate" {
        let vc = segue.destination as! UpdateViewController
        vc.loadViewIfNeeded()
        vc.UpdateTextLabel.text = TextField.text
    }
}

This will load the view and the text field before trying to access the text field.

One more thing, it's common practice for class names to start with an uppercase letter (like MyViewController) and variables to start with a lowercase letter (updateTextLabel instead of UpdateTextLabel).