![](/img/trans.png)
[英]How to update a custom section header without reloading the whole table view?
[英]How to draw a custom shape in the UIView for a table view header section?
我正在尝试在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
渲染正确。 我知道这一点是因为我可以看到 header 部分的颜色从默认颜色变为白色。 但是,我在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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.