显示在 containerView 中的 NSViewController 不会将自身与 Cocoa App Swift [Mac OS ] 中的容器边界对齐

NSViewController displayed inside a containerView doesn't align itself to the bounds of the Container in Cocoa App Swift [Mac OS ]

带容器视图的NSViewcontroller代码

@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

}

NS的代码ViewController在container view中显示

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

}

我添加了白色图层以更好地描述我的问题

我已经在情节提要中正确设置了容器视图的约束,并检查了容器视图是否也占据了整个 ViewController。

为什么我的 viewController 设置为容器视图的一部分而不是全部?

ContainerView 边界控制台图像

您的简历和完整 window 的初始大小为 480*270。那时,您的 vc2 大小也是正确的。但后来我调整了你的完整 window。 cv 调整大小但 vc2 不调整。

问题是当您使用约束时,它们会随着布局的变化而调整大小。但是在 vc2 中,你在一开始就给了它一个恒定的大小。这就是为什么即使您调整 window 的大小,它也不会调整大小。尝试以编程方式将约束分配给 vc2.view 以将其附加到其父视图 (cv)。这将确保 vc2.view 将随 cv.

调整大小

确保在 cv.addSubview(vc2.view) 之后分配约束。

查看 this library,这将在创建约束时删除大量样板代码。

如果您希望在调整 NSViewController(MainViewController) 大小时调整容器视图的大小,则只需将容器视图添加到主 NSViewcontroller 中,如屏幕截图所示

为您的容器视图提供以下 AutoLayout 约束: Leading、tralling、Top、Bottom 对超级视图的约束

最后将您的 vc2 连接到容器视图即可。

现在,当您调整 MainViewcontroller 大小时,您的容器视图会自动调整大小。无需在 MainViewController 中为容器视图编写代码。