我正在添加一个子视图(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)
}
它工作正常
你们中的任何人都知道为什么或如何使用superview调整子视图的大小?
我真的很感谢你的帮助
你将view.autoresizesSubviews
设置为true
,它告诉view
调整每个子视图的大小。但您还必须指定希望如何调整每个子视图的大小。你可以通过设置子视图的autoresizingMask
来做到这一点。由于你希望子视图的frame
继续匹配superview的bounds
,你希望子视图的width
和height
是灵活的,你希望它的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)
}
我找到了解决此问题的方法:
override func viewWillLayout() {
super.viewWillLayout()
newView.frame = view.bounds
}