Search code examples
iosswiftdropdownuicontainerview

Passing same variable to container view with different value


I have one button on main viewController which has default value nil which is associated by dropDown pod. On same viewController there is also a container view.

During first time loading, I get the default value of a variable from shared preferences and pass that value to container view by performSegue.

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if(segue.identifier == "dataToContainerView"){
    DispatchQueue.main.async {

   var secondVC = segue.destination as! secondViewController //container viewController
        secondVC.variable = self.variable  
    }
  }
}

Now I need to pass the value of same variable again by selecting from dropdown button by user.

 dropDown.selectionAction = { [unowned self] (index, item) in
        self.button.setTitle(item, for: UIControlState())
        self.variable = item
        print(item)
        self.performSegue(withIdentifier: "dataToContainerView", sender: nil)
  //performing segue to resend the new value of the variable.
    }

The above code performs properly till print(item). But I am getting the following error on performSegue.

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'There are unexpected subviews in the container view. Perhaps the embed segue has already fired once or a subview was added programmatically?

How should I pass the value to container view second time overriding first value with the help of dropDown pod?

update:- I need the variable value so that I can pass it to json parser on container viewController. And the code on container viewController re-executes.


Solution

  • You need to save a reference to your embedded controller so that you can update it again later. Do this in the first segue:

    // Declare a local variable in your parent container:
    var secondVC: secondViewController!
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "dataToContainerView"){
            DispatchQueue.main.async {
                self.secondVC = segue.destination as! secondViewController 
                //container viewController
                self.secondVC.variable = self.variable  
            }
        }
    }
    

    Then later when you need to update the variable you can just reference it directly:

    self.secondVC.variable = self.variable
    self.secondVC.viewDidLoad()