尝试为 UITableViewCell 绘制虚线边框

Trying to draw dashed border for UITableViewCell

我正在尝试使用以下代码为 UITableViewCells 绘制虚线底部边框:

func addDashedBottomBorder(to cell: UITableViewCell) {
    let width = CGFloat(2.0)
    let dashedBorderLayer: CAShapeLayer = CAShapeLayer()
    let frameSize = cell.frame.size
    let shapeRect = CGRect(x: 0, y: frameSize.height, width: frameSize.width*2, height: 1) 

    dashedBorderLayer.bounds = shapeRect
    dashedBorderLayer.position = CGPoint(x: 0, y: frameSize.height)
    dashedBorderLayer.strokeColor = UIColor.lightGray.cgColor
    dashedBorderLayer.lineWidth = width
    dashedBorderLayer.lineDashPattern = [9, 6]
    dashedBorderLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath

    cell.layer.addSublayer(dashedBorderLayer)
}

但是,我在虚线后面看到了一条奇怪的实线,如下所示:http://imgur.com/6kR9PgZ

我已经在 viewDidLoad

中设置了 tableView.separatorColor = UIColor.clear

知道为什么我把那条实线放在虚线后面吗?

Objective-C

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

在Swift

tableView.separatorStyle = .None

您使用 donted 行显示的行是默认的 TableViewCell 分隔符,您可以直接从界面构建器中将其删除,而无需编写任何代码。

在 interface builder select 你的 TableViewAttributes Insepector 中将 Separator 属性 设置为 None

试试这个

func addDashedBottomBorder(to cell: UITableViewCell) {

    let color = UIColor.lightGray.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 = kCALineJoinRound
    shapeLayer.lineDashPattern = [9,6]
    shapeLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: shapeRect.height, width: shapeRect.width, height: 0), cornerRadius: 0).cgPath

    cell.layer.addSublayer(shapeLayer)
}

输出

如果你写了

tableView.separatorStyle = .None

不过,你在 dassed 模式下得到了一条实线,然后 100% 它不是 tableview 分隔符。这是别的东西

check your Table background colour, When you clear separator color, a small space remains between cell. If you cell background color different color from table background color, it visible like a separator.