Search code examples
iosswiftuicontainerview

How do I get the property value from a container view in Swift


I have 1 UIViewController that contains a UIContainerView and a UIButton. Also, I have a UITableViewController (It has a UITextField and a UITextView) that is embedded in the UIContainerView in the UIViewController.

I'm trying to get the string values that will be available in TextField and in TextView.

enter image description here

I tried to use the segue to get the properties values, but I failed to do so, see the code below.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "TVCSegue" {
        let containerTVC = segue.destination as? FieldsTVC
        self.textField.text = FieldsTVC?.textField?.text
        self.textView.text = FieldsTVC?.textView?.text
    }
}

The code above has 'textField' and 'textView' as properties in the UIViewController to assign the values to.

But I believe that it doesn't work as I get the values before they changes. Please provide me with a functional way to do so.


Solution

  • When your main view loads, the container performs a segue to its assigned initial / root ViewController. At that point, you can get a reference to it:

    var theFieldsTVC: FieldsTVC?
    

    Now, in prepare for segue, assign that variable:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
        if segue.identifier == "TVCSegue" {
    
            if let vc = segue.destination as? FieldsTVC {
                theFieldsTVC = vc
            }
    
        }
    }       
    

    Then, you can:

    @IBAction func buttonTapped(_ sender: Any) {
    
        self.textField.text = theFieldsTVC?.textField?.text
        self.textView.text = theFieldsTVC?.textView?.text
    
    }