4
votes

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)

2
You can do this in viewDidLoad(). - Yevgeniy Leychenko
As Evgeniy has said, you can do it in viewDidLoad() - Rizwan Ahmed
Can you elaborate on this, it is a very vague answer. on viewDidLoad() how do I do that? The other answers mostly recommend using prepareforsegue which is what I will try - dvd.Void

2 Answers

1
votes

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.

1
votes

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.
        }
    }