CALayer,CAConstraints无效

问题描述 投票:0回答:1

尝试将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()

}

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

macos cocoa constraints calayer
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.