如何让 CAShapeLayer 与 swift 的约束一起工作?

How to get CAShapeLayer to work with constraints with swift?

我在 viewdidload 中看到了这个

rectShape1 = CAShapeLayer()

rectShape1.fillColor = UIColor.blueColor().CGColor
rectShape1.path = UIBezierPath(roundedRect: rectShape1.bounds, byRoundingCorners: .BottomLeft | .TopRight, cornerRadii: CGSize(width: 20, height: 20)).CGPath
redview.layer.addSublayer(rectShape1)


var constTop = NSLayoutConstraint(item: redview, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
view.addConstraint(constTop)

var constH = NSLayoutConstraint(item: redview, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 50)
redview.addConstraint(constH)

var constW = NSLayoutConstraint(item: redview, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 50)
redview.addConstraint(constW)

constH = NSLayoutConstraint(item: redview, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
view.addConstraint(constH)
rectShape1.frame = redview.bounds

这在 didlayoutsubviews 中

            self.rectShape1.frame = self.redview.bounds

我有与 gradientLayer 类似的东西,我工作得很好,有什么建议吗?

问题是在您创建贝塞尔曲线路径时 rectShape1.bounds.size 是 {0,0}。从 viewDidLoad 中删除创建路径的行,并将其移动到 viewDidLayoutSubviews

中设置框架后
override func viewDidLayoutSubviews() {
        self.rectShape1.frame = self.redview.bounds
        rectShape1.path = UIBezierPath(roundedRect: rectShape1.bounds, byRoundingCorners: .BottomLeft | .TopRight, cornerRadii: CGSize(width: 20, height: 20)).CGPath
    }