Search code examples
swift3childviewcontroller

How do I manage recurrent child UIViewControllers?


Scenario:

  1. I instantiate a UIViewController and added it to a containerViewController.
  2. I dismiss (remove) this child
  3. I select this same child to display again.

My Concern: I wish to create a single child UIViewController instance.
But It appears that I would create an additional instance of the child view controller per 'case' iteration, which I do not want.

Question: Does Swift already handle this?
...or must I check for the current view controller's instance prior to making it a child?

If I have to check for its existance, then I'll have to make 'viewController' global for all cases.

enter image description here

enter image description here


Solution

  • No Swift doesn't handle this automatically. You must check the existing child view controllers to prevent adding duplicates.

    You could use code like this:

    if let controller = parent.childViewControllers.filter { $0 is CountriesViewController }.first {
        // use existing child controller here
    }
    else {
        // create new child controller and add it to parent here
    }