问题
i got this in 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
and this in didlayoutsubviews
self.rectShape1.frame = self.redview.bounds
i have similar stuff with gradientLayer and i works fine, any suggestions?
回答1:
The problem is that rectShape1.bounds.size is {0,0} at the time you create the bezier path. Remove the line where you create the path from viewDidLoad, and move it to after you set the frame in 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
}
来源:https://stackoverflow.com/questions/30565416/how-to-get-cashapelayer-to-work-with-constraints-with-swift