iosswiftviewcontrollercontainer-view

Adjust the size of a container view's View Controller programatically in iOS


I've set up a container view for some Container View controller programatically like this

var containerView : UIView!
var controller :    UIViewController!


override func viewDidLoad() {
    super.viewDidLoad()


    containerView = UIView()
    containerView.frame = CGRect(x: 0 , y: 200 , width: 375, height: 400)
    self.view.addSubview(containerView)


    controller = storyboard!.instantiateViewController(withIdentifier: "containerVC")
    addChildViewController(controller)
    controller.didMove(toParentViewController: self)
    containerView.addSubview(controller.view)

}

In the storyboard I give the container View Controller a custom size by selecting the Container View Controller -> Utilities -> Size Inspector -> Selecting Freeform in the view tab and giving it a custom size.

enter image description here

The problem is that the containerVC's view doesn't fit inside the container view since it will always have a default size of (375 , 667).

enter image description here

How do I change the size of the Container View Controller so that it has the specified size?


Solution

  • You forget to give frame size for containerVC's view. Do it just after you add it to superview.