【问题标题】:How to draw a custom shape in the UIView for a table view header section?如何在 UIView 中为表格视图标题部分绘制自定义形状?
【发布时间】:2020-12-11 09:49:43
【问题描述】:

我正在尝试在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 中完成的绘图没有被渲染。我在想层实例化中可能缺少配置?

【问题讨论】:

    标签: swift uitableview calayer uibezierpath cashapelayer


    【解决方案1】:

    这解决了我的问题:

       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
        }
    

    【讨论】:

      猜你喜欢
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多