更改自定义tableViewCell的背景颜色

我想改变我的细胞的背景颜色

我看到其他问题,但他们不符合我的情况

我想做一个通知tableView

例如,如果用户已经读取单元格,单元格的背景颜色将变为白色

如果不是,颜色是黄色的

开始时

我设置了颜色

-(void)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{ if(read[[indexPath row]]) [cell.backView setBckgroundColor:[UIColor whiteColor]; else [cell.backView setBckgroundColor:[UIColor redColor]; } 

它的工作原理,然后我想改变颜色

 tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{ read[[indexPath row]] = yes; [cell.backView setBckgroundColor:[UIColor whiteColor]; cell.name.text = @"test"; } 

它也可以

但是,如果我select其他细胞,它改变为原始的颜色

看来只能同时改变一个单元格的颜色

不pipe我用

 cell.backgroundColor cell.contentView.backgroundColor cell.backView 

它得到了同样的结果,任何人都可以帮助我


编辑4/20 20:13

我设置了阅读

 tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath 

抱歉误导,我更新代码

和我select其他单元格后,我不调用[tableView重载]

所以我不认为这是原因

顺便说一下,一切(如标签)可以改变,但背景颜色

如果我select单元格,则通过导航跳转到其他屏幕


结论第一

 tableView: cellForRowAtIndexPath: is well 

 tableView: willDisplayCell: is well too 

他们都可以改变背景颜色

但是在需要绘制新的单元格或重新加载tableView时执行

我仍然混淆为什么我可以更改didselectionRowAtIndexPath中的标签,但我无法更改颜色

使用tableView: willDisplayCell:方法更改颜色

 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { if (...){ //do your stuff. [cell.backView setBckgroundColor:[UIColor redColor]; } else { [cell.backView setBckgroundColor:[UIColor whiteColor]; } } 

我想你想设置你的variables“读”为YES

tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath

我想你只使用一个variables来logging状态,只是因为你简化它在这里发布,否则你可能想logging每个单元格的状态与单独的variables。

您需要更新单元索引处的对象的“读取”属性。

 tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath { [cell.backView setBckgroundColor:[UIColor whiteColor]; currentObjectForThisCell.read = YES; } 

然后:

 -(void)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { if(currentObjectForThisCell.read) [cell.backView setBckgroundColor:[UIColor whiteColor]; else [cell.backView setBckgroundColor:[UIColor redColor]; } 

在你编辑的代码中,当你select单元格时,你将读取标志设置为YES,并将颜色改为白色,这很好,但是在你的cellForRowAtIndexPath:你设置单元格的读标志YES为红色,NO设置为白色与您的didSelectRowAtIndexPath:方法中的行为相反。

尝试获取didSelectRowAtIndexPath中的选定单元格

– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

/ /设置select索引的属性

 UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; cell.backgroundColor = [UIColor redColor]; 

}

你有没有调用reloadData的“didSelectRowAtIndexPath”的tableView设置读取属性,并重新加载tableView