扩展一下UITableView
extension UITableView {
/// section圆形边框
func setCornerRadiusSection(radius: CGFloat = 10.0, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// 圆角半径
let cornerRadius = radius
// 下面为设置圆角操作(通过遮罩实现)
let sectionCount = self.numberOfRows(inSection: indexPath.section)
cell.layer.mask = nil
// 当前分区有多行数据时
if sectionCount > 1 {
switch indexPath.row {
// 如果是第一行,左上、右上角为圆角
case 0:
cell.bbCornerCorner(corner: [.topLeft,.topRight], radii: cornerRadius)
// 如果是最后一行,左下、右下角为圆角
case sectionCount - 1:
cell.bbCornerCorner(corner: [.bottomLeft,.bottomRight], radii: cornerRadius)
default: break
}
}
//当前分区只有一行行数据时
else {
//四个角都为圆角(同样设置偏移隐藏首、尾分隔线)
cell.bbCornerCorner(corner: [.allCorners], radii: cornerRadius)
}
}
}
extension UIView {
/// 自定义控件圆角位置 如:只左上 左下有圆角
func bbCornerCorner(corner: UIRectCorner, radii: CGFloat){
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: radii, height: radii))
maskLayer.path = maskPath.cgPath
layer.mask = maskLayer
}
}
记得重写一下cell的Frame
class TableViewCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
}
override var frame:CGRect{
didSet {
var newFrame = frame
newFrame.origin.x += 10
newFrame.size.width -= 20
super.frame = newFrame
}
}
}
使用
- 遵循一下UITableViewDelegate协议
- 然后
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// 绘制Section边框
tableView.setCornerRadiusSection(willDisplay: cell, forRowAt: indexPath)
}
看下效果图