将 CAConstraints 与 NSView 层一起使用

Using CAConstraints with NSView layers

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

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

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))

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

您没有在代码中设置 CAConstraintLayerManager:

layer.layoutManager = CAConstraintLayoutManager()

查看片段:

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