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

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

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

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

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


当前回答

我可以想到三种方法:

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.

明白吗?

其他回答

在阅读其他人的答案后再读这篇文章

我想警告所有想要使用像添加标题这样的解决方案来达到间隔目的的人。如果你这样做,你将不能动画单元格的插入,删除等。例如,如果您使用该方法,您可能会得到这种错误

无效更新:无效的节数。更新后(6)表视图中包含的section数量必须等于更新前(5)表视图中包含的section数量,加上或减去插入或删除的section数量(插入0个,删除0个)。

如果你需要动画插入和删除行,我会在单元格本身添加这个空间。如果你担心高亮显示,那么你可以重写方法 func setHighlighted(_ highlighted: Bool, animated: Bool) 然后自己设置高亮

如果你不想使用任何标题,使用标题作为间距也可以。否则,这可能不是最好的主意。我在想的是创建一个自定义单元格视图。

例子:

用笔尖 在代码中

在自定义单元格中,创建一个带有约束的背景视图,这样它就不会填充整个单元格,给它一些填充。

然后,使tableview背景不可见,并删除分隔符:

// Make the background invisible
tableView.backgroundView = UIView()
tableView.backgroundColor = .clear

// Remove the separators
tableview.separatorStyle = .none

我重写这个函数是UITableViewCell的子类,它对我来说工作正常

override func layoutSubviews() {
      super.layoutSubviews()
      //set the values for top,left,bottom,right margins
      let margins = UIEdgeInsets(top: 5, left: 8, bottom: 5, right: 8)
      contentView.frame = contentView.frame.inset(by: margins)
      contentView.layer.cornerRadius = 8
}

只是把对我有用的答案添加到答案池中。

我已经在TableViewCell中添加了一个视图(紫色视图),我使用它作为单元格的内容视图。并限制紫色视图在顶部和底部都有填充,或者其他你想要的,但我认为这种方式创造了更多的灵活性。

试着调查一下 ——(UIEdgeInsets) layoutMargins; 在单元格上