Skip to content

Instantly share code, notes, and snippets.

@michaelevensen
Last active September 5, 2022 07:27
Show Gist options
  • Save michaelevensen/3bbd36e417e463c01368ff5669a428c0 to your computer and use it in GitHub Desktop.
Save michaelevensen/3bbd36e417e463c01368ff5669a428c0 to your computer and use it in GitHub Desktop.
Embed a UIViewController in Container View programatically
// Instantiate
self.mapViewController = self.storyboard?.instantiateViewController(withIdentifier: "MapViewController") as? MapViewController
if let mapViewController = self.mapViewController {
// Add to Container View
self.mapViewContainerView.addSubview(mapViewController.view)
self.addChildViewController(mapViewController)
mapViewController.didMove(toParentViewController: self)
}
}
@Streebor
Copy link

Sorry to jump in, but according to Apple's documentation willMove(toParentViewController:) is called when you call addChildViewController(_:), so it doesn't look like you have to call it explicitly...

When your custom container calls the addChildViewController(_:) method, it automatically calls the willMove(toParentViewController:) method of the view controller to be added as a child before adding it.

https://developer.apple.com/documentation/uikit/uiviewcontroller/1621381-willmove

He is correct. I have tested this and in the above example the willMode is called 2x

@michaelevensen
Copy link
Author

👍

@arturponomarenko
Copy link

arturponomarenko commented Sep 5, 2022

willMove documentation:

When your custom container calls the addChild(_:) method, it automatically calls the willMove(toParent:) method of the view controller to be added as a child before adding it.

Looks like there is no need to call the willMove method since just after that you call the addChildViewController

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment