问题描述
我试图在headerView
中为给定部分在UITableviewController
中绘制自定义形状。这是我的代码:
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
}
UIView
正确呈现。我知道这一点是因为我可以看到标题部分的颜色从默认颜色变为白色。但是,我在CAShapeLayer
中所做的绘图未渲染。我在想层实例中可能缺少配置吗?
解决方法
这解决了我的问题:
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
}