有没有办法增加UITableViewCell之间的间距?

我已经创建了一个表,每个单元格只包含一个图像。图像被这样分配给单元格:

cell.imageView.image = [myImages objectAtIndex:indexPath.row];

但这使得图像放大并适合整个细胞,并且图像之间没有间隔。

或者让我们这样说,图像的高度是50,我想在图像之间增加20的间距。有什么办法可以做到吗?


当前回答

这篇文章很有帮助,它和其他答案差不多,但是总结和简洁

https://medium.com/@andersongusmao/left-and-right-margins-on-uitableviewcell-595f0ba5f5e6

其中,他只将它们应用于左侧和右侧,但UIEdgeInsetsMake初始化允许为所有四个点添加填充。

func UIEdgeInsetsMake(_ top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat) -> UIEdgeInsets Description Creates an edge inset for a button or view. An inset is a margin around a rectangle. Positive values represent margins closer to the center of the rectangle, while negative values represent margins further from the center. Parameters top: The inset at the top of an object. left: The inset on the left of an object bottom: The inset on the bottom of an object. right: The inset on the right of an object. Returns An inset for a button or view

注意,UIEdgeInsets也可以用来实现同样的效果。

Xcode 9.3/Swift 4

其他回答

我可以想到三种方法:

Create a custom table cell that lays out the view of the entire cell in the manner that you desire Instead of adding the image to the image view, clear the subviews of the image view, create a custom view that adds an UIImageView for the image and another view, perhaps a simple UIView that provides the desired spacing, and add it as a subview of the image view. I want to suggest that you manipulate the UIImageView directly to set a fixed size/padding, but I'm nowhere near Xcode so I can't confirm whether/how this would work.

明白吗?

在单元格中添加一个内部视图,然后将自己的视图添加到单元格中。

使用节而不是行 每个section应该返回一行 使用indexPath分配单元格数据。Section,而不是row 实现UITableView委托方法hightforheader并返回你想要的间距

将section中的行数更改为1 您更改了区段数而不是行数

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        1
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

这里是行与行之间的行距

 func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }

这是实际的解决方案

使用节而不是行因为每一行都有一个节所以你可以给页眉留出空间节脚这是代码,把它粘贴到你的视图控制器类中,在这里你创建tableview outlet

如果你想要顶部间距使用heightForHeaderInSection 如果你想要底部间距,只需使用heightForFooterInSection如下所示

复制粘贴即可

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 20
}

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let v = UIView()
    v.backgroundColor = UIColor.clear
    return v
}

    func numberOfSections(in tableView: UITableView) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }