话不多少,上代码:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// 在该方法下对每个section设置阴影
// 圆角角度
let radius = kMarginMid
// 设置cell 背景色为透明
cell.backgroundColor = .clear
// 创建layer
let normalLayer = CAShapeLayer()
// 获取显示区域大小
let bounds = cell.bounds.insetBy(dx: kMarginMid, dy: 0)
// cell的backgroundView
let normalBgView = UIView(frame: bounds)
// 获取每组行数
let rowNum = tableView.numberOfRows(inSection: indexPath.section)
// 贝塞尔曲线
var bezierPath = UIBezierPath()
if rowNum == 1 {
// 一组只有一行(四个角全部为圆角)
bezierPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius))
normalBgView.clipsToBounds = false
} else {
normalBgView.clipsToBounds = true
if indexPath.row == 0 {
let top = indexPath.section == 0 ? kMarginMin : RW(5)
let rect = bounds.inset(by: UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0))
// 每组第一行(添加左上和右上的圆角)
bezierPath = UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: radius, height: radius))
} else if indexPath.row == rowNum - 1 {
let rect = bounds.inset(by: UIEdgeInsets(top: 0, left: 0, bottom: RW(5), right: 0))
// 每组最后一行(添加左下和右下的圆角)
bezierPath = UIBezierPath(roundedRect: rect, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: radius, height: radius))
} else {
// 每组不是首位的行不设置圆角
bezierPath = UIBezierPath(rect: bounds)
}
}
// 阴影
normalLayer.shadowColor = UIColor.black.cgColor;
normalLayer.shadowOpacity = 0.15
normalLayer.shadowOffset = CGSize(width: 0, height: 1)
normalLayer.path = bezierPath.cgPath
normalLayer.shadowPath = bezierPath.cgPath
// 设置填充颜色
normalLayer.fillColor = UIColor.white.cgColor
// 添加图层到nomarBgView中
normalBgView.backgroundColor = UIColor.clear
// 如果是第一个分区,那么需要再额外加一层
if indexPath.section == 0 && indexPath.row == 0 {
normalBgView.backgroundColor = APP_MainColor
let basicLayer = CAShapeLayer()
basicLayer.path = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: RW(22.5), height: RW(22.5))).cgPath
basicLayer.fillColor = UIColor.white.cgColor
// normalBgView.layer.insertSublayer(basicLayer, at: 0)
basicLayer.addSublayer(normalLayer)
normalBgView.layer.insertSublayer(basicLayer, at: 0)
} else {
normalBgView.layer.insertSublayer(normalLayer, at: 0)
}
cell.backgroundView = normalBgView
}