TableView的Section切圆角在实际的项目开发中是比较常见的,出现频率最高是在个人中心页面。大体的效果如图所示

8C72ABFA-4EB5-4A37-A956-1BE18CEFB3F3.png
这种方式的UITableView一般设置UITableViewStyle为grouped:
UITableView(frame: self.view.bounds, style: .grouped
这种方式是主要特点是:
- 1、section的row只有一行的时候,四周都切圆角;
- 2、多个row的时候,只在第一个row的左上、右上切圆角,最后一个row的左下、右下切圆角,中间均为不切圆角。
补充: tableView的每个section和row的分割线在实际的开发中,一般设计出来的会跟系统的有出入,建议设置 tableView.separatorStyle = .none ,然后再自定义cell或者写个baseCell来的添加分割线,这样可以灵活的设置。
推荐两种方式:
- 1、通过UITableViewHeaderFooterView来实现,切圆角与cell是分开的:
在UITableViewHeaderFooterView来创建一个TableHeaderView和TableFooterView,分别在里面添加一个UIView,然后在TableHeaderView里添加的UIView切左上、右上, TableFooterView里添加的UIView切左下、右下。
- 2、直接设置在cell的layer上insertSublayer的方式(
这里主要介绍)
我写了一个UITableViewCell+Extension,使用起来也比较简单:
在swift中:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.lgl_tableView(tableView: tableView, cellCornerRadius: 30, forRowAt: indexPath)
}
在OC中使用:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.lgl_tableView(tableView: tableView, cellCornerRadius: 30, forRowAt: indexPath)
}
下面是完整的代码,可以直接copy到项目中使用。
import UIKit
extension UITableViewCell {
///给UITableView的Section切圆角 在willDisplaycell方法里面调用
@objc func lgl_tableView(tableView:UITableView, cellCornerRadius cornerRadius: CGFloat, forRowAt indexPath: IndexPath) {
//圆率
let cornerRadii = CGSize(width: cornerRadius, height: cornerRadius)
// 每一段的行数
let numberOfRows = tableView.numberOfRows(inSection: indexPath.section)
//绘制曲线
var bezierPath: UIBezierPath?
if numberOfRows == 1 {
bezierPath = lgl_bezierRoundedPath(.allCorners, cornerRadii)
} else {
switch indexPath.row {
case 0: //第一个切左上右上
bezierPath = lgl_bezierRoundedPath([.topLeft, .topRight], cornerRadii)
case numberOfRows-1: //最后一个切左下右下
bezierPath = lgl_bezierRoundedPath([.bottomLeft, .bottomRight], cornerRadii)
default:
bezierPath = lgl_bezierPath()
}
}
lgl_cellAddLayer(bezierPath!)
}
///切圆角
private func lgl_bezierRoundedPath(_ corners:UIRectCorner, _ cornerRadii:CGSize) -> UIBezierPath {
return UIBezierPath.init(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: cornerRadii)
}
///不切圆角
private func lgl_bezierPath() -> UIBezierPath {
return UIBezierPath.init(rect: self.bounds)
}
///添加到cell上
private func lgl_cellAddLayer(_ bezierPath:UIBezierPath) {
self.backgroundColor = .clear
//新建一个图层
let layer = CAShapeLayer()
//图层边框路径
layer.path = bezierPath.cgPath
//图层填充色,也就是cell的底色
// layer.fillColor = UIColor.red.cgColor
layer.fillColor = UIColor.white.cgColor
// layer.strokeColor = UIColor.red.cgColor
self.layer.insertSublayer(layer, at: 0)
}
}