1

Using this example I am trying to add a dashed border to my UITableView.

Trying to draw dashed border for UITableViewCell

But it does not work. It shows nothing.

func addDashedBottomBorder(to cell: UITableViewCell) {
    let color = UIColor.black.cgColor

    let shapeLayer:CAShapeLayer = CAShapeLayer()
    let frameSize = cell.frame.size
    let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: 0)

    shapeLayer.bounds = shapeRect
    shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = color
    shapeLayer.lineWidth = 2.0
    shapeLayer.lineJoin = kCALineJoinRound
    shapeLayer.lineDashPattern = [9,6]
    shapeLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: shapeRect.height, width: shapeRect.width, height: 0), cornerRadius: 0).cgPath

    cell.layer.addSublayer(shapeLayer)
}

I am using this method in cellForRowAt but it shows me nothing and in viewDidLoad, table.separatorStyle = .none.

Kazunori Takaishi
  • 2,268
  • 1
  • 15
  • 27
Jhony
  • 187
  • 1
  • 4
  • 16

1 Answers1

0

From the below 2 lines of your code:

    shapeLayer.lineJoin = kCALineJoinRound
    shapeLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: shapeRect.height, width: shapeRect.width, height: 0), cornerRadius: 0).cgPath

kCALineJoinRound is making upper and lower dash lines but they are overlapping due to the height of UIBezierPath is 0. So, Updated your code as:

    shapeLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: shapeRect.height, width: shapeRect.width, height: 1), cornerRadius: 0).cgPath

It will hide the lower line and you will get the desired result.

Best Solution:

Rather than hiding lower dash line, you can correct it by providing just lineDashPhase to your CAShapeLayer, as:

    shapeLayer.lineJoin = kCALineJoinRound
    shapeLayer.lineDashPhase = 3.0 // Add "lineDashPhase" property to CAShapeLayer
    shapeLayer.lineDashPattern = [9,6]
    shapeLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: shapeRect.height, width: shapeRect.width, height: 0), cornerRadius: 0).cgPath

Received line is:

enter image description here

Ankit Jayaswal
  • 5,549
  • 3
  • 16
  • 36