uitableviewcell背景

Nee*_*esh 1 iphone objective-c uitableview

我有一个UItableView(分组样式).我想自定义它,使它看起来像一个"粘贴它"或一个带有黄色背景界面的"发布它".

因此添加了以下代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UIView *backgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
    backgroundView.backgroundColor = [UIColor yellowColor];
    cell.backgroundView = backgroundView;
    cell.textLabel.backgroundColor=[UIColor yellowColor];
} 
Run Code Online (Sandbox Code Playgroud)

这实际上有效.我能够实现黄色背景,但缺少分隔线.some1可以帮助我吗?

这是最好的方法吗?或者我应该为单元格创建一个图像并将其用作backgroundView?

PKC*_*oft 6

实际上,上述答案都没有(我相信)是正确的.根据doco:

注意:如果要更改单元格的背景颜色(通过UIView声明的backgroundColor属性设置单元格的背景颜色),则必须tableView:willDisplayCell:forRowAtIndexPath:在委托方法中进行,而不是在tableView:cellForRowAtIndexPath:数据源中进行.组样式表视图中单元格背景颜色的更改在iOS 3.0中具有与以前版本的操作系统不同的效果.它现在影响圆角矩形内的区域而不是它外面的区域.

因此,而不是打电话setBackgroundColortableView:cellForRowAtIndexPath:,你应该这样在做tableView:willDisplayCell:forRowAtIndexPath::

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
ShoppingList *object = (ShoppingList*)[self.fetchedResultsController objectAtIndexPath:indexPath];

    if ([object isComplete] == YES) {
        [cell setBackgroundColor:[UIColor greenColor]];
    } else {
        [cell setBackgroundColor:[UIColor clearColor]];
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现它完美无缺,并且与表格单元格渲染的其余部分的工作方式相符.无需添加任何背景视图或任何其他视图.