[Swfit 5] 设置UITableViewCell和Section的圆角和边距

本文介绍了如何在Swift 5中为UITableViewCell和Section设置圆角及边距,特别适用于没有头尾的情况。文章提供了一种方法,解决了在section中有多个cell时设置圆角的问题,可以在`willDisplay cell`或`estimatedHeightForRowAt`方法内调用。同时,文章提及对于带有头尾的section圆角设置,读者可以参考原作者的另一篇文章。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此文是按照原文整理直接拷贝代码使用
原文出处原文出处

此方法针对没有头尾的情况,如果带有头尾请查看原作者另一篇文章
带有头尾的section圆角

开发中常用到cell两边带有边距和圆角,如果section里有多个cell,直接设置圆角会出问题,此文把两种情况总结为一个方法,在 cellForRowwillDisplayCell 方法里直接调用即可

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
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值