UITableView 的使用中,经常出现卡片的使用情况,需要按组切圆角。代码如下:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// 获取行数
let sectionRows = tableView.numberOfRows(inSection: indexPath.section)
// 设置圆角数值
let radius = 8.0
// 创建 CAShapeLayer
let layer = CAShapeLayer()
let bounds = cell.bounds
layer.frame = bounds
if indexPath.row == 0, sectionRows == 1 { // 一个为一组,四个圆角
let path = UIBezierPath.init(roundedRect: bounds, cornerRadius: radius)
layer.path = path.cgPath
cell.layer.mask = layer
} else if indexPath.row == 0 { // 第一个cell,左上,右上切圆角
let path = UIBezierPath.init(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: .init(width: radius, height: radius))
layer.path = path.cgPath
cell.layer.mask = layer
} else if indexPath.row + 1 == sectionRows { // 最后一个cell,左下,右下切圆角
let path = UIBezierPath.init(roundedRect: bounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: .init(width: radius, height: radius))
layer.path = path.cgPath
cell.layer.mask = layer
}
}