在 table 视图单元格中添加虚线底部边框与 iOS 中的文本随机重叠

Adding a dashed bottom border to table view cell overlaps with text randomly in iOS

我正在使用以下代码向表格视图单元格添加虚线自定义底部边框。它现在随机地与内容重叠。有时,边框不显示。

class AppTableCell: UITableViewCell {
    var shapeLayer: CAShapeLayer?
    var isBorderAdded = false

    func isBottomBorderAdded() -> Bool {
        return isBorderAdded
    }

    func getBottomBorderShapeLayer() -> CAShapeLayer {
        return self.shapeLayer!
    }

    func setBottomBorderShapedLayer(_ layer: CAShapeLayer) {
        self.shapeLayer = layer
    }
}

从上面 class 扩展表格视图单元格并在 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 方法中调用下面的函数。

func addDashedBottomBorder(to cell: AppTableCell) {
    let color = UIColor.init(red: 191/255, green: 191/255, blue: 191/255, alpha: 1.0).cgColor
    let shapeLayer:CAShapeLayer = CAShapeLayer()
    let frameSize = cell.frame.size
    let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: 0)
    shapeLayer.bounds = shapeRect
    shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = color
    shapeLayer.lineWidth = 2.0
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round
    shapeLayer.lineDashPhase = 3.0
    shapeLayer.lineDashPattern = [9,6]
    shapeLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: shapeRect.height, width: shapeRect.width, height: 0), cornerRadius: 0).cgPath
    if (cell.isBorderAdded) {
        cell.shapeLayer!.removeFromSuperlayer()
    }
    cell.shapeLayer = shapeLayer
    cell.isBorderAdded = true
    cell.layer.addSublayer(shapeLayer)
}

如何在每个单元格的末尾正确显示虚线底边框?

您正在使用固定位置在单元格图层中添加子图层:

shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height)
[...]
cell.layer.addSublayer(shapeLayer)

因此它不会粘在您手机的底部。

您可以在每次单元格高度变化时更新该层的位置,但从性能和简单性的角度来看,我的建议是使用自动布局。

在单元格的底部添加一个子视图,添加约束以使其固定,并且只添加一次(在 awakeFromNib 中,例如,如果它是在 IB 中设计的)内部的 dashedLayer。