Search code examples
swiftuitableviewcalayeruibezierpathcashapelayer

How to draw a custom shape in the UIView for a table view header section?


I am trying to draw a custom shape in the headerView for a given section in my UITableviewController. Here is my code:

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        10
    }

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView()
    view.backgroundColor = .white
    
    let rect = view.bounds
    
    let bezier = UIBezierPath()
    bezier.move(to: CGPoint(x: rect.minX, y: rect.midY))
    bezier.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
    bezier.stroke()
    
    let shape = CAShapeLayer()
    shape.path = bezier.cgPath
    shape.strokeColor = UIColor.red.cgColor
    
    view.layer.addSublayer(shape)
    return view
}

The UIView is rendered correctly. I know this because I can see the color of the header sections change from the default color to white. However, the drawing I have done in the CAShapeLayer is not being rendered. I am thinking possibly there is configuration missing in the layer instantiation?


Solution

  • This solved my problem:

       class ViewWithLine : UIView {
    
          override func draw(_ rect: CGRect) {
            let y: CGFloat = rect.midY
            let x1: CGFloat = rect.minX + 5
            let x2: CGFloat = rect.maxX - 5
    
            UIColor.lightGray.setStroke()
    
            let b = UIBezierPath()
            b.lineWidth = 0.5
            b.move(to: CGPoint(x: x1, y: y))
            b.addLine(to: CGPoint(x: x2, y: y))
            b.stroke()
        }
     }
    
        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
                5
            }
        
        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            let view = ViewWithLine()
            view.backgroundColor = .white
            return view
        }