I am trying to draw dashed line with rounded corners around a view like this:
class DashedLineView: UIView {
override func draw(_ rect: CGRect) {
let path = UIBezierPath(roundedRect: rect, cornerRadius: 8)
UIColor.clear.setFill()
path.fill()
UIColor.red.setStroke()
path.lineWidth = 3
let dashPattern : [CGFloat] = [3, 3]
path.setLineDash(dashPattern, count: 2, phase: 0)
path.stroke()
}
}
The result is:
As you can see there is a problem with corners, any idea how to fix it?
Updated:
Using @Jon Rose answer DashedLineView
looks like this now:
class DashedLineView: UIView {
private let borderLayer = CAShapeLayer()
override func awakeFromNib() {
super.awakeFromNib()
borderLayer.strokeColor = UIColor.red.cgColor
borderLayer.lineDashPattern = [3,3]
borderLayer.backgroundColor = UIColor.clear.cgColor
borderLayer.fillColor = UIColor.clear.cgColor
layer.addSublayer(borderLayer)
}
override func draw(_ rect: CGRect) {
borderLayer.path = UIBezierPath(roundedRect: rect, cornerRadius: 8).cgPath
}
}