From a parent controller I call another child ( popoverContent )
with self.present
, the child controller is a typical view in the form of a popup that at the end I close with a dismiss but I want to pass some data to the parent view.
Called within the code of the parent controller:
self.present(popoverContent, animated: true, completion: nil )
I close the child view ( popoverContent
) with a button action
@IBAction func exitButtonAction(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
How can I pass a parameter of type String, or Int, or dictionary to the parent view after closing the child view with dismiss ?
Passing data from a child ViewController to a parent can be done by a protocol hosted on the parent and "manipulated" by the child but I find it can be a bit of a hassle to implement these functions.
One way you can manipulate your variables is to: 1. Create a class in which you store the data you need. 2. Create a static variable to access said class from any controller without having to create a new object of this same class. 3. Implement set and get to be able to access your data.
Something like this:
The way you can retrieve the information is, for example from the viewWillAppear() method:
Prints: Value through get method: Hello world Value extracted directly from the class: Hello world
The most logical thing would be to make a protocol, you can look at this: protocols, passing information from other views to one from an action
But if what you want is something simpler, and you are going to pass a couple of variables, you can apply the same concept as a delegate. In popoverContent you create a var that is of the type of the parent, you create the popoverContent, to that variable you assign the value of the parent, you show it and before closing it, popoverContent has a reference to the parent, so I could modify the parent variable that you would like
In the popoverContent:
In parent, you create and assign:
By the time you go to close the popover: