3

我正在添加一个子视图(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)
}

它工作正常

在此处输入图像描述 但是当我调整窗口大小时,子视图没有调整大小。

在此处输入图像描述

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

我会非常感谢你的帮助

4

2 回答 2

4

您设置view.autoresizesSubviewstrue,它告诉view调整其每个子视图的大小。但是您还必须指定如何调整每个子视图的大小。您可以通过设置子视图的autoresizingMask. 由于您希望子视图frame继续与父视图匹配bounds,因此您希望子视图的widthandheight灵活,并且您希望其 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)
}
于 2019-04-29T17:28:39.020 回答
1

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

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

    }
于 2019-04-29T16:20:14.667 回答