How to get CAShapeLayer to work with constraints with swift?

对着背影说爱祢 提交于 2019-12-25 06:14:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!