可可雨燕:子视图不能调整为超级视图

时间:2019-04-26 21:28:49

标签: swift cocoa nsview nsviewcontroller xcode10.2

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

效果很好

enter image description here 但是当我调整窗口大小时,子视图没有调整大小。

enter image description here

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

非常感谢您的帮助

2 个答案:

答案 0 :(得分:2)

您将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)
}

答案 1 :(得分:0)

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

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

    }