在单元格上设置backgroundView之后,UITableViewCells之间的垂直空间

时间:2011-03-24 00:19:23

标签: ios uitableview

我正在实现具有自定义背景的UITableViewCells,并在点击时展开。

我将自定义视图设置为我的UITableViewCells backgroundView :(在RowForIndexPath中)

if (cell == nil) {
    CGRect f = CGRectMake(0.0f, 0.0f, 300.0f, 50.0f);

    cell = [[UITableViewCell alloc] initWithFrame:f reuseIdentifier:cellIdentifier];

    UIView *back = [[UIView alloc] initWithFrame:CGRectMake(10.0f, 10.0f, 300.0f, 50.0f)];
    back.layer.cornerRadius = 8.0f;
    [back setBackgroundColor:[UIColor blackColor]];

这很好用,通过设置backgroundView而不是contentView,我的backgroundView会扩展以适应单元格扩展后的新大小(在点击后更改heightForRowAtIndexPath中的高度)。

我现在的问题是我希望我的细胞之间有几个像素的垂直空间。使用上述方法将使圆形黑色单元格“背靠背”显示。

有没有办法在细胞之间添加垂直空间,或者我可以采取完全不同的方法来获得所需的细胞外观?

提前致谢。

1 个答案:

答案 0 :(得分:3)

为了在单元格之间显示空格并避免您遇到的“背靠背”问题,您可以添加UIView,其中包含以下框架CGRectMake(0, 0, 320, 1),并将背景设置为灯光灰色表示标准单元格分隔符,或者如果您只想要一些填充,则可以使背景清晰。

我个人喜欢使用界面构建器,但您当然可以通过编程方式执行此操作。

UIView *cellSeparator = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320 ,1)];
[cellSeparator setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin |
                                   UIViewAutoresizingFlexibleRightMargin | 
                                   UIViewAutoresizingFlexibleWidth];       
[cellSeparator setContentMode:UIViewContentModeTopLeft];    
[cellSeparator setBackgroundColor:[UIColor lightGrayColor]];
[cell addSubview:cellSeparator];
[cellSeparator release];

我将cellSeparator设置在单元格顶部的原因是因为效果实际上是介于第一行和最后一行之间的单元格。此外,设置autoresizingMask和contentMode以确保在对UITableViewCell进行大小更改时正确调整单元格分隔符非常重要。如果单元格中有任何元素从x=0 y=0开始,则需要将它们向下移动到单元格分隔符的高度加上一些额外的像素用于填充,以便分隔符不会通过任何元素运行细胞。