Search code examples
iosswiftuiscrollviewuicontainerview

UIStoryboardSegue embed


What exactly does the embedding segue in a UIView (added as a container view) in interface builder do? I'm trying to embed a ViewController programmatically because I want to choose between two different ones. I guess I set the limiting constraints of the Container View correct because when I add the child view controller with a embedding segue in the storyboard, everything works fine but as soon as I embed it with the following code, the View Controller overlaps the bottom constraint of the containerview and it messes up my layout..

let viewController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "MyViewController")
self.containerView.addSubview(viewController.view)
self.addChildViewController(viewController)
NSLayoutConstraint.activate([
    viewController.view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
    viewController.view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
    viewController.view.topAnchor.constraint(equalTo: containerView.topAnchor),
    viewController.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
])

viewController.didMove(toParentViewController: self)

Solution

  • Thanks to @Dinesh Balasubramanian I got the following code now which works:

    let viewController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "MyViewController")
    self.containerView.addSubview(viewController.view)
    self.addChildViewController(viewController)
    viewController.view.frame = containerView.bounds
    viewController.didMove(toParentViewController: self)