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

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

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

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

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


当前回答

我实现在单元格之间增加间距的方法是使numberOfSections =“您的数组计数”,并使每个部分只包含一行。然后定义headerView和它的height。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return yourArry.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return cellSpacingHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *v = [UIView new];
    [v setBackgroundColor:[UIColor clearColor]];
    return v;
}

其他回答

我的情况是我使用自定义UIView viewForHeader在节也hightforheader在节返回常量高度说40,问题是当没有数据时,所有的头视图被彼此触摸。所以我想在没有数据的部分之间留出空间,所以我通过将“tableview style”平面改为“Group”来固定。这对我很有效。

如果你不想改变你的表视图的section和行号(就像我做的那样),下面是你要做的:

1)在表格单元格视图的底部添加一个ImageView。

2)使它与表格视图的背景颜色相同。

我已经在我的应用程序中这样做了,它工作得很好。干杯!: D

你可以像这样简单地在代码中使用constraint:

class viewCell : UITableViewCell 
{

@IBOutlet weak var container: UIView!



func setShape() {
    self.container.backgroundColor = .blue
    self.container.layer.cornerRadius = 20
    container.translatesAutoresizingMaskIntoConstraints = false
    self.container.widthAnchor.constraint(equalTo:contentView.widthAnchor , constant: -40).isActive = true
           self.container.heightAnchor.constraint(equalTo: contentView.heightAnchor,constant: -20).isActive = true
           self.container.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
           self.container.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true

    }
}

添加子视图(容器)并在其中放入其他元素是很重要的。

我遇到了麻烦,让它与背景颜色和附属视图一起在单元格中工作。最后不得不:

1)使用带有背景颜色的UIView设置单元格的背景视图属性。

let view = UIView()
view.backgroundColor = UIColor.white
self.backgroundView = view

2)在layoutSubviews中重新定位这个视图,添加间距的想法

override func layoutSubviews() {
    super.layoutSubviews()
    backgroundView?.frame = backgroundView?.frame.inset(by: UIEdgeInsets(top: 2, left: 0, bottom: 0, right: 0)) ?? CGRect.zero
}

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

例子:

用笔尖 在代码中

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

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

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

// Remove the separators
tableview.separatorStyle = .none