此文是按照原文整理直接拷贝代码使用
原文出处原文出处
此方法针对没有头尾的情况,如果带有头尾请查看原作者另一篇文章
带有头尾的section圆角
开发中常用到cell两边带有边距和圆角,如果section里有多个cell,直接设置圆角会出问题,此文把两种情况总结为一个方法,在 cellForRow
或 willDisplayCell
方法里直接调用即可
private func setCornerRadiusForSectionCell(cell: UITableViewCell, indexPath: IndexPath) {
//圆角半径
let cornerRadius:CGFloat = 10.0
//下面为设置圆角操作(通过遮罩实现)
let sectionCount = tableView.numberOfRows(inSection: indexPath.section)
let shapeLayer = CAShapeLayer()
cell.layer.mask = nil
//当前分区有多行数据时
if sectionCount > 1 {
switch indexPath.row {
//如果是第一行,左上、右上角为圆角
case 0:
var bounds = cell.bounds
bounds.origin.y += 1.0 //这样每一组首行顶部分割线不显示
let bezierPath = UIBezierPath(roundedRect: bounds,
byRoundingCorners: [.topLeft,.topRight],
cornerRadii: CGSize(width: cornerRadius,height: cornerRadius))
shapeLayer.path = bezierPath.cgPath
cell.layer.mask = shapeLayer
//如果是最后一行,左下、右下角为圆角
case sectionCount - 1:
var bounds = cell.bounds
bounds.size.height -= 1.0 //这样每一组尾行底部分割线不显示
let bezierPath = UIBezierPath(roundedRect: bounds,
byRoundingCorners: [.bottomLeft,.bottomRight],
cornerRadii: CGSize(width: cornerRadius,height: cornerRadius))
shapeLayer.path = bezierPath.cgPath
cell.layer.mask = shapeLayer
default:
break
}
}
//当前分区只有一行行数据时
else {
//四个角都为圆角(同样设置偏移隐藏首、尾分隔线)
let bezierPath = UIBezierPath(roundedRect:
cell.bounds.insetBy(dx: 0.0, dy: 2.0),
cornerRadius: cornerRadius)
shapeLayer.path = bezierPath.cgPath
cell.layer.mask = shapeLayer
}
}
设置cell边距,自定义cell的类里重写 frame
方法
override var frame: CGRect {
didSet {
var newFrame = frame
newFrame.origin.x += 10
newFrame.size.width -= 20
super.frame = newFrame
}
}