The code of the NSViewcontroller with container view

@IBOutlet weak var cv: NSView!
override func viewDidLoad() {
    super.viewDidLoad()
      let vc2 = storyboard?.instantiateController(withIdentifier: "vc2") as! VC2
    addChild(vc2)
    vc2.view.frame=cv.bounds
    cv.addSubview(vc2.view)
    cv.wantsLayer=true
    cv.layer?.backgroundColor=NSColor.red.cgColor

}

The code of the NSViewController to be displayed in the container view

   override func viewDidLoad() {
    super.viewDidLoad()
    self.view.wantsLayer=true
    self.view.layer?.backgroundColor=NSColor.white.cgColor

}

I have added the white layer to describe my question better enter image description here

I have set the constraints for container view properly in the storyboard and have checked that as well the container view occupies the whole ViewController.

Why is my viewController set to only a portion of the container view and not fully?

ContainerView Bounds Console image enter image description here

Initial size of your cv and complete window is 480*270. And at that point, your vc2 size is also correct. But then I resize your complete window. The cv resizes but not the vc2.

2 Answers

3
kerry On Best Solutions

The problem is that when you are using constraints, they resize with changes in layout. But in vc2, you have given it a constant size at the start. Which is why even if you resize the window, it does not get resized. Try programmatically assigning constraints to vc2.view to attach it to its superview (cv). This will make sure that vc2.view will resize with cv.

Make sure to assign constraints after cv.addSubview(vc2.view).

Check out this library which will remove a lot of boiler plate code while creating constraints.

-1
Community On

If you want your container view resize when you resize your NSViewController(MainViewController) then just add container view to your main NSViewcontroller as shown in screenshot

enter image description here

Provide following AutoLayout constraints to your container view : Leading , tralling ,Top , Bottom constraint to super view

enter image description here

And Last connect your vc2 to container view that's it.

enter image description here

Now, Your container view resize automatically when you resize your MainViewcontroller. No need to write code for container view in MainViewController.