Swift5 UITableView Section圆形边框

扩展一下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
        }
    }
}

使用

  1. 遵循一下UITableViewDelegate协议
  2. 然后
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        // 绘制Section边框
        tableView.setCornerRadiusSection(willDisplay: cell, forRowAt: indexPath)
    }

看下效果图

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 更新:2018.05.24 整理了一下demo:SwiftDemo 最近比较忙,没什么时间写,断断续续写一点。 U...
    YvanLiu阅读 34,462评论 6 57
  • UITableView简介UITableViewCell简介以及重用原理介绍UITableViewCell的几种循...
    Mark_Guan阅读 4,669评论 1 8
  • 1.概念 它是基于UIScrollView的列表互动类。使用UITableView可以在屏幕上显示单元格的列表,每...
    栖息于旷野阅读 4,966评论 0 0
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,798评论 1 32
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 12,721评论 28 53