CALayer,CAConstraints无效

时间:2017-12-28 17:48:00

标签: macos cocoa constraints calayer

尝试将CAConstraints与CALayer一起使用。经过多次尝试和搜索,我无法让它发挥作用。打印后:超级图层具有框架(可见颜色),子图层有约束但没有绘制任何内容(子图层没有框架)。

这来自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()

}

超级层(蓝色),表现正常,调整大小等等。子层(红色),没有。
如果我设置子图层框架,它将绘制,但将保持静态。

1 个答案:

答案 0 :(得分:0)

此问题的目的是使用窗口调整大小调整子图层的大小,其方式与使用NSLayoutConstraints的子视图的行为相匹配。

在查看Apple sample code并将layoutManager设置为超级层后,我得到了关于它的运行时间投诉(鉴于,超级层不是我的,但直接view.layer )。这开始感觉约束处理子层之间的关系而不是遵循视图本身的约束。

此时,标题可能会产生误导,但如果你最终在这里尝试完成上述行为,我终于使用autoresizingMask解决了这个问题。 我的NSViewController在Storyboard中设置了NSLayoutConstraints的NSImageView。从那里,我只需要设置初始大小和宽高比。

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