swift - 如何在 UIView 中为 TableView 标题部分绘制自定义形状?

标签 swift uitableview calayer uibezierpath cashapelayer

我正在尝试在 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
    }

关于swift - 如何在 UIView 中为 TableView 标题部分绘制自定义形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63532505/

相关文章:

ios - 大 UIImage 未显示在 UIImageView 中

iOS swift 。自日期以来的时间

objective-c - 检查 CALayer 是否已经添加为子层

ios - UITableView 单元格在滚动时混合

swift - 两个不同单元格的 TableView 相同的 cellForRowAt 用法

ios - 如何在 iOS 中创建带有阴影和 subview 的 UIimageView

ios - 动画 CALayer 的 shadowPath 属性

swift - 无法标记属性@IBInspectable

ios - Swift:编辑模式,将 editButtonItem() 链接到 IBAction

swift - 调整容器 View 的高度以匹配 subview 的高度