swift-UITableView 圆角cell

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    let cornerRadius: CGFloat = 4.0
    cell.backgroundColor = UIColor.clear

    let layer = CAShapeLayer()
    let backgroundLayer = CAShapeLayer()
    let pathRef = CGMutablePath()
    let bounds = cell.bounds;

    let numberOfRows = self.tableView.numberOfRows(inSection: indexPath.section)

    var needSeparator = false
    if (indexPath.row == 0 && numberOfRows == 1) {
        pathRef.addRoundedRect(in: bounds, cornerWidth: cornerRadius, cornerHeight: cornerRadius)
    }else if (indexPath.row == 0) {
        pathRef.move(to: CGPoint(x: bounds.minX, y: bounds.maxY))
        pathRef.addArc(tangent1End: CGPoint(x: bounds.minX, y: bounds.minY), tangent2End: CGPoint(x: bounds.midX, y: bounds.minY), radius: cornerRadius)
        pathRef.addArc(tangent1End: CGPoint(x: bounds.maxX, y: bounds.minY), tangent2End: CGPoint(x: bounds.maxX, y: bounds.midY), radius: cornerRadius)
        pathRef.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
        needSeparator = true;
    } else if indexPath.row == (numberOfRows-1) {
        pathRef.move(to: CGPoint(x: bounds.minX, y: bounds.minY))
        pathRef.addArc(tangent1End: CGPoint(x: bounds.minX, y: bounds.maxY), tangent2End: CGPoint(x: bounds.midX, y: bounds.maxY), radius: cornerRadius)
        pathRef.addArc(tangent1End: CGPoint(x: bounds.maxX, y: bounds.maxY), tangent2End: CGPoint(x: bounds.maxX, y: bounds.midY), radius: cornerRadius)
        pathRef.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
    } else {
        pathRef.addRect(bounds)
        needSeparator = true
    }

    layer.path = pathRef
    backgroundLayer.path = pathRef
    layer.fillColor = UIColor.white.cgColor

    if (needSeparator) {
        let lineLayer = CALayer()
        let lineHeight = (1.0 / UIScreen.main.scale)
        lineLayer.frame = CGRect(x: bounds.minX + 10, y: bounds.size.height-lineHeight, width: bounds.size.width - 10, height: lineHeight)
        lineLayer.backgroundColor = self.tableView.separatorColor?.cgColor
        layer.addSublayer(lineLayer)
    }

    let roundView = UIView(frame: bounds)
    roundView.layer.insertSublayer(layer, at: 0)
    roundView.backgroundColor = UIColor.clear
    cell.backgroundView = roundView
}

你可能感兴趣的:(swift-UITableView 圆角cell)