4

I have a container view in my Storyboard that displays another view controller that I already programmed and stuff. I want to communicate between the main View Controller and the contained-view controller. I know how to use delegates and I am comfortable with using them, however I normally set up delegates when I initialize a ViewController, however in this case I don't know where to apply this, since the view controller is already there per the storyboard. Normally I would do something like this:

class HomeVC: UIViewController {
    func initializeVC() {
        resultsVC = self.storyboard?.instantiateViewController(withIdentifier: "resultsView") as! GoalsVC
        resultsVC.calcDelegate = self //I set the "HomeVC" as the Delegate since it has all the functions I need
    }
}

As mentioned above, since I never really created this view controller via code, I don't know how to assign a delegate (specially setting the delegate to "self" (where Self is the main View Controller)

rmaddy
  • 314,917
  • 42
  • 532
  • 579
dvd.Void
  • 339
  • 1
  • 5
  • 21

2 Answers2

1

As you are using storyboard for container view. There is a segue with embed type. Give this segue a identifier, say MyContainedViewControllerSegueId

Then in prepare(for segue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "MyContainedViewControllerSegueId" {
            // here you get your contained view controller as `segue.destination`
            // cast it your subclassed view controller
            // use delegate on that subclassed view controller for communication purpose.
        }
    }
Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44
1

You can assign delegate in prepareforsegue. Like below code

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "container_segue") {
        let controller = segue.destination as! containerController
        controller.delegate = self
    }
}

When project runs, this method called automatically because we had created segue in the storyboard.

By using segue.identifier you can check for which controller segue is going to happen and accordingly you can achieve your requirement.

Indrajeet
  • 5,490
  • 2
  • 28
  • 43