Cocoa Swift: 子视图未随父视图调整大小

Cocoa Swift: Subview not resizing with superview

我正在添加一个子视图(NSView),这是我的代码:

override func viewDidAppear() {
    self.view.needsDisplay = true
    let newView = NSView()
    newView.autoresizesSubviews = true
    newView.frame = view.bounds
    newView.wantsLayer = true
    newView.layer?.backgroundColor = NSColor.green.cgColor
    view.addSubview(newView)
}

而且效果很好

但是当我调整 window 的大小时,子视图没有调整。

你们中有人知道为什么或如何使用父视图调整子视图的大小吗?

非常感谢你的帮助

我找到了解决此问题的方法:

override func viewWillLayout() {
        super.viewWillLayout()
        newView.frame = view.bounds

    }

您将 view.autoresizesSubviews 设置为 true,这会告诉 view 调整其每个子视图的大小。但是您还必须指定您希望如何调整每个子视图的大小。您可以通过设置子视图的 autoresizingMask 来做到这一点。由于您希望子视图的 frame 继续匹配父视图的 bounds,您希望子视图的 widthheight 灵活,并且您希望其 X 和 Y 边距固定(为零)。因此:

override func viewDidAppear() {
    self.view.needsDisplay = true
    let newView = NSView()

    // The following line had no effect on the layout of newView in view,
    // so I have commented it out.
    // newView.autoresizesSubviews = true

    newView.frame = view.bounds

    // The following line tells view to resize newView so that newView.frame
    // stays equal to view.bounds.
    newView.autoresizingMask = [.width, .height]

    newView.wantsLayer = true
    newView.layer?.backgroundColor = NSColor.green.cgColor
    view.addSubview(newView)
}