D3migod D3migod - 1 month ago 25
Swift Question

How to set up UIBezierPath border for view in ios?

I created

CAShapeLayer
border for view using the below code:

func addBorderToWebView() {
borderShape = CAShapeLayer()
borderShape.path = UIBezierPath(rect: webView.frame).cgPath
borderShape.lineWidth = CGFloat(2)
borderShape.bounds = borderShape.path!.boundingBox
borderShape.strokeColor = UIColor(red: 68/255, green: 219/255, blue: 94/255, alpha: 1.0).cgColor
borderShape.position = CGPoint(x: borderShape.bounds.width/2, y: borderShape.bounds.height/2)
webView.layer.addSublayer(borderShape)
}


I right and bottom border lines are out of the frame, you can see it on the image below. However, if I define
borderWidth
property of
webView.layer
, everything appears to be showed fine. That is why I make a conclusion, that the problem is not in layout constraints. How should I configure
UIBezierPath
(or
CAShapeLayer
) to make the border be showed correctly? Thank you for any help!

CAShapeLayer border

Answer

Try to replace this

borderShape.path = UIBezierPath(rect: webView.frame).cgPath

with this:

borderShape.path = UIBezierPath(rect: webView.bounds).cgPath

Another possible cause of the problem is that webView's frame is not updated yet when you set it to borderShape. You can try to do self.view.updateLayoutIfNeeded() prior to adding border shape. If it doesn't help override the following method:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    updateBorderShape()
}

func updateBorderShape() {
    borderShape.bounds = borderShape.path!.boundingBox
    borderShape.position = CGPoint(x: borderShape.bounds.width/2, y: borderShape.bounds.height/2)
}

This will make sure that every time your frames are updated, border shape is updated as well.

Comments