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

标签 ios uitableview

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

我正在将自定义 View 设置为我的 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 中的高度)。

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

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

提前致谢。

最佳答案

为了显示单元格之间的空间并避免您遇到的“背靠背”问题,您可以添加一个具有以下框架的 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 开始,您需要将它们向下移动到单元格分隔符的高度,再加上一些额外的填充像素,这样分隔符就不会' 遍历单元格中的所有元素。

关于ios - 在单元格上设置 backgroundView 后 UITableViewCells 之间的垂直空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5413269/

相关文章:

ios - 识别谁在 iOS 中执行了手势

ios - 如何在Cocoa Touch Library中添加UIWebView并在应用程序中使用它

ios - 使用自动布局支持以编程方式更改 UITableView 位置

ios - Swift - UIViewController 内的 UITableView,不调用 UITableView 函数

ios - TableView 无法正常工作

ios - 顺时针旋转 iOS 图像

iphone - 无法删除 Three20 中的 navigationItem.leftBarButtonItem

iphone - 每 30 分钟执行一次选择器

ios - UITableViewCell UILabel 多行对齐

ios - 删除节标题和 uitableviewcell 之间的分隔符