Cocoa Swift:Subview没有使用superview调整大小

问题描述 投票:0回答: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

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

我真的很感谢你的帮助

swift cocoa nsview nsviewcontroller xcode10.2
2个回答
2
投票

你将view.autoresizesSubviews设置为true,它告诉view调整每个子视图的大小。但您还必须指定希望如何调整每个子视图的大小。你可以通过设置子视图的autoresizingMask来做到这一点。由于你希望子视图的frame继续匹配superview的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)
}

0
投票

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

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

    }
© www.soinside.com 2019 - 2024. All rights reserved.