我要添加一个子视图(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)
}
效果很好
你们中的任何人都知道为什么或如何通过超级视图调整子视图的大小吗?
非常感谢您的帮助
答案 0 :(得分:2)
您将view.autoresizesSubviews
设置为true
,这告诉view
调整其每个子视图的大小。但是,您还必须指定如何调整每个子视图的大小。您可以通过设置子视图的autoresizingMask
来实现。由于您希望子视图的frame
继续与父视图的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)
}
答案 1 :(得分:0)
我找到了解决此问题的方法:
override func viewWillLayout() {
super.viewWillLayout()
newView.frame = view.bounds
}