UITableView Section圆角
extension UITableView {
/// section圆角 需要在 `WillDisplayCell`中调用
/// - Parameters:
/// - cell: cell 对象
/// - indexPath: index
/// - cornerRadius: 圆角值
/// - inset: inset 偏移,比如 cell 含有 containerView
/// - Important: 如果 Cell 有事件触发Cell高度改变,借助`tableView.beginUpdate`和`tableView.beginUpdate`来进行行高改变时,由于此次更新不走 `willDisplayCell`方法,可能导致Cell部分显示有问题(解决:使用 reload()或者不使用该方法)
func sectionCornerWillDisplayCell(_ cell: UITableViewCell, forRowAt indexPath: IndexPath, cornerRadius: CGFloat, inset: UIEdgeInsets = .zero) {
var pathRect = cell.bounds
pathRect = pathRect.inset(by: inset)
let numberOfRow = numberOfRows(inSection: indexPath.section)
let headerView: UIView? = self.delegate?.tableView?(self, viewForHeaderInSection: indexPath.section)
clearCellMask(cell)
// 绘制曲线
let row = indexPath.row
let cornerSize = CGSize(width: cornerRadius, height: cornerRadius)
var bezierPath: UIBezierPath?
if headerView != nil {
// 存在 header
if row == 0, numberOfRow == 1 {
// 一个 section 只有一行, 四边圆角
bezierPath = UIBezierPath(roundedRect: pathRect, byRoundingCorners: [.allCorners], cornerRadii: cornerSize)
} else if row == 0 {
// 第一行 如果需要圆角由 header 处理,需要实现 willdisappearHeader 方法中做 layer 圆角
bezierPath = UIBezierPath(roundedRect: pathRect, byRoundingCorners: [.topLeft, .topRight], cornerRadii: cornerSize)
} else if row == numberOfRow-1 {
// 组的最后一行
bezierPath = UIBezierPath(roundedRect: pathRect, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: cornerSize)
} else {
// 中间的行
return
}
} else {
if row == 0, numberOfRow == 1 {
// 一个 section 只有一行, 四边圆角
bezierPath = UIBezierPath(roundedRect: pathRect, byRoundingCorners: [.allCorners], cornerRadii: cornerSize)
} else if row == 0 {
bezierPath = UIBezierPath(roundedRect: pathRect, byRoundingCorners: [.topLeft, .topRight], cornerRadii: cornerSize)
} else if row == numberOfRow-1 {
// 组的最后一行
bezierPath = UIBezierPath(roundedRect: pathRect, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: cornerSize)
} else {
// 中间的行
return
}
}
guard let bezierPath = bezierPath else {
return
}
let layer = CAShapeLayer()
// MARK: - 后期实现边框阴影
// 阴影颜色 #395b8e0c
// layer.shadowColor = UIColor.red.cgColor
// layer.shadowPath = bezierPath.cgPath
// layer.shadowRadius = 5
layer.path = bezierPath.cgPath
cell.layer.mask = layer
}
private func clearCellMask(_ cell: UITableViewCell) {
if let mask = cell.layer.mask, let shapeLayer = mask as? CAShapeLayer, shapeLayer.path != nil {
cell.layer.mask = nil // 避免影响复用 cell
}
}
}