Embed UIViewController inside a UIView

As others said you can't embed a viewcontroller view inside a view. What you can do is embed a ViewController inside another ViewController as a ChildViewController.

Try replacing your newView code with:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
var controller: UIViewController = storyboard.instantiateViewController(withIdentifier: "testView") as UIViewController

//add as a childviewcontroller
 addChildViewController(controller)

 // Add the child's View as a subview
 self.view.addSubview(controller.view)
 controller.view.frame = view.bounds
 controller.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

 // tell the childviewcontroller it's contained in it's parent
  controller.didMove(toParentViewController: self)

EDIT: To change how and where the childviewcontroller appears, simply update its frame. for example to make it half the height and anchored to the bottom:

controller.view.frame = CGRect(x: 0, y: view.center.y, width: view.size.width, height: view.size.height * 0.5) 

Updated to the latest swift and using a extension of the UIViewController class :

extension UIViewController {
    func embed(_ viewController:UIViewController, inView view:UIView){
        viewController.willMove(toParent: self)
        viewController.view.frame = view.bounds
        view.addSubview(viewController.view)
        self.addChild(viewController)
        viewController.didMove(toParent: self)
    }
}

You can have a generic method like:

func embed(_ viewController:UIViewController, inParent controller:UIViewController, inView view:UIView){
   viewController.willMove(toParent: controller)
   viewController.view.frame = view.bounds
   view.addSubview(viewController.view)
   controller.addChild(viewController)
   viewController.didMove(toParent: controller)
}

Hope it helps

Tags:

Uiview

Swift