将CAConstraints与NSView图层一起使用

时间:2018-07-18 03:21:24

标签: macos layer nsview

我希望NSView的子层随视图一起增长/缩小,以便其框架自动匹配视图的边界,而无需显式重置它。

假设视图的主层始终与视图匹配,我尝试了以下代码:

let layer = self.layer!  // It is guaranteed to exist
layer.backgroundColor = NSColor.white
layer.name = "MainLayer"
let sublayer = CALayer()
sublayer.backgroundColor = NSColor.black

layer.addSublayer(sublayer)

sublayer.addConstraint(CAConstraint.init(attribute: .width, relativeTo: "MainLayer", attribute: CAConstraintAttribute.width))
sublayer.addConstraint(CAConstraint.init(attribute: .height, relativeTo: "MainLayer", attribute: CAConstraintAttribute.height))

猜猜看:除非明确设置了子帧,否则看不到子层。 还尝试了相反方向的约束:从层到子层-相同的结果

1 个答案:

答案 0 :(得分:0)

您未在代码中设置CAConstraintLayerManager:

layer.layoutManager = CAConstraintLayoutManager()

请参见中的代码段:

https://developer.apple.com/documentation/quartzcore/caconstraintlayoutmanager