Macos CALayer,列车不工作了
试图使用Caconstraint和CALayer。经过多次尝试和搜索,我无法让它工作。打印后:超层有帧(颜色可见),子层有约束,但没有绘制任何内容(子层有零帧) 这是来自Macos CALayer,列车不工作了,macos,cocoa,constraints,calayer,Macos,Cocoa,Constraints,Calayer,试图使用Caconstraint和CALayer。经过多次尝试和搜索,我无法让它工作。打印后:超层有帧(颜色可见),子层有约束,但没有绘制任何内容(子层有零帧) 这是来自NSViewController override func viewDidAppear() { super.viewDidAppear() let layer = CALayer() layer.backgroundColor = NSColor.red.cgColor
NSViewController
override func viewDidAppear() {
super.viewDidAppear()
let layer = CALayer()
layer.backgroundColor = NSColor.red.cgColor
// centerView is just an NSView, first child of the main view.
self.centerView.wantsLayer = true
self.centerView.layer?.layoutManager = CAConstraintLayoutManager()
self.centerView.layer?.addSublayer(layer)
self.centerView.layer?.backgroundColor = NSColor.blue.cgColor
layer.addConstraint(CAConstraint(attribute: CAConstraintAttribute.midX, relativeTo: "superlayer", attribute: CAConstraintAttribute.midX))
layer.addConstraint(CAConstraint(attribute: CAConstraintAttribute.midY, relativeTo: "superlayer", attribute: CAConstraintAttribute.midY))
layer.addConstraint(CAConstraint(attribute: CAConstraintAttribute.width, relativeTo: "superlayer", attribute: CAConstraintAttribute.width))
layer.addConstraint(CAConstraint(attribute: CAConstraintAttribute.height, relativeTo: "superlayer", attribute: CAConstraintAttribute.height))
layer.setNeedsDisplay()
self.centerView.layer?.setNeedsDisplay()
}
超级层(蓝色)表现正常,正在调整大小。子层(红色),无任何内容。如果我设置子层框架,它将绘制,但将保持静态。此问题的目的是使用窗口大小调整子层的大小,以与使用
NSLayoutConstraints
的子视图的行为相匹配的方式
在查看一个苹果并将layoutManager
设置为superlayer之后,我收到了一个运行时投诉(假设superlayer不是我的,而是直接视图.layer
)。这开始让人觉得约束处理子层之间的关系,而不是视图本身的约束
在这一点上,标题可能有误导性,但如果您最终在这里尝试完成上述行为,我最终通过使用autoresizingMask
My
NSViewController
在序列图像板中有一个带有NSLayoutConstraints
设置的NSImage视图。从那里,我只需要设置初始大小和纵横比
// 'self' is an NSImageView subclass
self.currnetLayer = CALayer()
self.currnetLayer.bounds = self.bounds
self.currnetLayer.frame.origin = CGPoint.zero // Initially, origin was negative here.
self.currnetLayer.autoresizingMask = [.layerWidthSizable, .layerHeightSizable]
self.currnetLayer.contentsGravity = kCAGravityResizeAspect // Keep aspect ratio
// ...
// Setting some animation here
// ...
self.layer?.addSublayer(self.currnetLayer)