2017-12-28 22 views
0

CALayerでCAConstraintsを使用しようとしています。多くの試みと検索の後、私はそれを働かせることはできません。印刷後:スーパーレイヤーにはフレーム(色で表示)があり、サブレイヤーには制約がありますが、何も描画されません(サブレイヤーにはフレームがありません)。 CALayer、CAConstraints not working

これは、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() 

} 

スーパーレイヤ(青)からのものである、OK行動リサイズ、すべてされます。副層(赤)、何もない。
サブレイヤフレームを設定すると描画されますが、静止したままになります。

答えて

0

この質問の目的は、NSLayoutConstraintsを使用してサブビューの動作に一致するように、ウィンドウのサイズを変更してサブレイヤのサイズを変更することでした。

アップルsample codeを見て、layoutManagerをスーパーレイヤーに設定した後、私はそれについて実行時の苦情を受けました(スーパーレイヤーは私のものではなく、直接view.layerです)。これは、制約がサブレイヤ間の関係を扱い、ビュー自体の制約に従わないように感じ始めました。

この時点で、タイトルが誤解を招く可能性がありますが、ここで上記の動作を達成しようとすると、autoresizingMaskを使用して解決しました。
私のNSViewControllerには、ストーリーボードに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)