UITableViewCell 左右边距

UITableViewCell margin left and right

我想制作这样的细胞。我使用 swift.

但我不知道如何在单元格的右侧和左侧添加边距。

你知道如何在截面上做同样的边缘效果吗? (当有多个cell时,接触的边缘不圆润)

当我使用 contentInset 时:

self.tableView.contentInset = UIEdgeInsetsMake(0, -15, 0, 0)

self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, -15)

从您的屏幕截图看来,您正尝试使用分组 table 视图来执行此操作。为此,您应该使用 UITableView 添加到 UIViewController 而不是 UITableViewController.

要设置插图,您只需将 table 视图的 constraints/frame 设置为从左右边缘稍微向内,并将视图的背景颜色设置为 UIColor.groupTableViewBackgroundColor()

然后在 cellForRowAtIndexPath 你可以这样说:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cornerRadius:CGFloat = 5.0

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

        // Configure your cell

        let sectionCount = tableView.numberOfRowsInSection(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
            }
            return cell
        }
        else
        {
            let bezierPath = UIBezierPath(roundedRect: CGRectInset(cell.bounds,0.0,2.0), cornerRadius: cornerRadius)
            shapeLayer.path = bezierPath.CGPath
            cell.layer.mask = shapeLayer
            return cell
        }
    }

您只需根据行的索引路径和节中的行数应用掩码。如果您有动态调整大小的单元格,您可能需要将掩码应用到您的 UITableViewCell 子类。

您应该得到如下结果:

自 iOS 13.0 以来,有一种新的 tableview 样式“Inset grouped”正是这样做的: https://developer.apple.com/documentation/uikit/uitableview/style/insetgrouped