Here you can see the view which is inside the TableViewell:
Here is the code for adding dashed border:
func addDashedBorder()
{
let color = UIColor(displayP3Red: 178.0/255.0, green: 181.0/255.0, blue: 200.0/255.0, alpha: 1.0).cgColor
let shapeLayer:CAShapeLayer = CAShapeLayer()
let shapeRect = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
shapeLayer.bounds = shapeRect
shapeLayer.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color
shapeLayer.lineWidth = 2
shapeLayer.lineJoin = CAShapeLayerLineJoin.round
shapeLayer.lineDashPattern = [6,3]
shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 4).cgPath
self.layer.addSublayer(shapeLayer)
}
I’m calling this function inside the awake from nib like this:
view.addDashedBorder()
.
2
Answers
Reason for issue: You are calling your border adding code from awakeFromNib.
Solution: The right place to do this is
func layoutSubviews()
layoutSubviews() gets called when the size of any subview will be changed or the frames of views/subviews gets updated first time.
This is the right place to add border or your view, and make sure it will only one call of adding border because layoutSubviews will get multiple calls if the frame of any subview will change.**
Much easier approach…
Subclass
UIView
and put the border-related code inside it:Now you don’t need any sort of
view.addDashedBorder()
calls.