How to properly destroy a child UIViewController?

I have my mainController (parent) and my menuController (child).

I call the menuController with

addChild(child)
view.addSubview(child.view)
child.didMove(toParent: self)

The child dismisses itself with:

self.dismiss(animated: true, completion: nil)

The question I have, is how do I clean up the child within the parent? Surely I have to do something?

Answered by Frameworks Engineer in 694696022

The UIViewController.dismiss(animated:completion:) method is used when the view controller is presented modally (i.e. with UIViewController.present(_:animated:completion:). It shouldn't be used when removing a child view controller (in which the child view controller's view is embedded within a parent/"container" view controller).

To remove a child view controller, you essentially call the corresponding methods in reverse.

child.willMove(toParent: nil)
child.view.removeFromSuperview()
child.removeFromParent()

A handy guide to this can be found here: https://developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html

Accepted Answer

The UIViewController.dismiss(animated:completion:) method is used when the view controller is presented modally (i.e. with UIViewController.present(_:animated:completion:). It shouldn't be used when removing a child view controller (in which the child view controller's view is embedded within a parent/"container" view controller).

To remove a child view controller, you essentially call the corresponding methods in reverse.

child.willMove(toParent: nil)
child.view.removeFromSuperview()
child.removeFromParent()

A handy guide to this can be found here: https://developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html

How to properly destroy a child UIViewController?
 
 
Q