UITableViewCell的背景颜色

Ben*_*ard 1 cocoa-touch uitableview ios

我正在使用IB中设置的基本表格视图单元格.我应用的唯一自定义是在cellForRowAtIndexPath中,我只是设置单元格标签的背景颜色(而不是单元格本身的颜色).

    [[cell textLabel] setBackgroundColor:[UIColor yellowColor]];
Run Code Online (Sandbox Code Playgroud)

首次绘制表格时,不应用背景颜色.当我向下滚动,这因为他们被吸引应用到新的细胞.同样,如果我向上滚动,顶部单元格将使用正确的背景颜色重新绘制.

这背后的解释是什么?

在此输入图像描述 在此输入图像描述

编辑 - 这是我的cellForRowAtIndexPath,以及IB中的设置:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
ItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ItemCell2"];
[[cell textLabel] setBackgroundColor:[UIColor yellowColor]];            
return cell;
Run Code Online (Sandbox Code Playgroud)

}

在此输入图像描述

Tar*_*ark 5

你必须使用

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
Run Code Online (Sandbox Code Playgroud)

来自文档:

表视图在使用单元格绘制行之前将此消息发送到其委托,从而允许委托在显示单元格对象之前对其进行自定义.此方法为委托提供了覆盖表视图前面设置的基于状态的属性的机会,例如选择和背景颜色.