話不多少庐船,上代碼:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// 在該方法下對每個section設(shè)置陰影
// 圓角角度
let radius = kMarginMid
// 設(shè)置cell 背景色為透明
cell.backgroundColor = .clear
// 創(chuàng)建layer
let normalLayer = CAShapeLayer()
// 獲取顯示區(qū)域大小
let bounds = cell.bounds.insetBy(dx: kMarginMid, dy: 0)
// cell的backgroundView
let normalBgView = UIView(frame: bounds)
// 獲取每組行數(shù)
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 {
// 每組不是首位的行不設(shè)置圓角
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
// 設(shè)置填充顏色
normalLayer.fillColor = UIColor.white.cgColor
// 添加圖層到nomarBgView中
normalBgView.backgroundColor = UIColor.clear
// 如果是第一個分區(qū),那么需要再額外加一層
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
}