Search code examples
iosswiftuitableviewuipageviewcontroller

Passing data from embedded PageViewController to parent View Controller


I'm working on an app that includes a "Representative Finder" that will allow someone to enter their address in a UITextField or select a state from a PickerView to see their government representatives. I have a main ViewController that will display the results after a user submits one of the aforementioned options. Over this, I have imposed a ContainerView into which I have embedded a PageViewController that has two pages; one that includes a UITextField and button to search by address, and the other that includes a PickerView and a Button that searches by state. The PageView is currently connected to the TableView via an embed transition, however, when I try to reference the parent table view controller in the PageViewController, it says the PVC has no parent, even though the ViewController identifies the PageViewController as its child. My question is: what is the proper way to pass variables FROM a child PageViewController to its container?

EDIT: I've tried the following, but it doesn't work:

In my PageViewController:

protocol SearchFinderDelegate: class
{
    func getResults(results: String)
}

class LawSearchWindow: UIPageViewController
{
     weak var newDelegate: SearchFinderDelegate?

  viewDidLoad()
   {

       /*Attempt to initialize newDelegate*/
       newDelegate=self
       newDelegate?.getResults(results: “test123”)
  }}

And in my Main VC class, I have:

func getResults(results: String)
{
    print(results)
}

UPDATE: When I try make the 'newDelegate=self' declaration, it tells me 'Cannot assign value of type 'VC name' to type 'Delegate Name'


Solution

  • The proper way would be to create a delegate protocol and have the parent conform to it (which the child then has a reference to as a weak property) or pass in a completion handler callback block to the child and have the child call that. Generally, you don't want to be directly referencing a parent from its child.