如何在选择UITableView行时更改颜色?

问题描述:

我环顾四周寻找答案,但尚未找到有效的工作。我所要做的就是能够更改背景颜色或我选择的UITableView行的图像。如何在选择UITableView行时更改颜色?

我习惯于在选择一行时转换视图,但这次我希望能够更改那些行属性。我知道我想更改哪一行,使用indexPath.row,但我不知道如何改变行的外观,因为cellForRowAtIndexPath方法已被调用!

怎样才能改变颜色?

+0

你用'[tableView reloadData]'重新加载tableview吗? – 2011-02-23 22:39:28

+0

嗯,我想这会工作,但然后我不知何故必须通过我选择的索引值...它可以工作,但它似乎应该有一个更优雅的解决方案 – 2011-02-23 22:44:06

你会做这样的:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    //First you get the cell you want to change 
    UITableViewCell* theCell = [tableView cellForRowAtIndexPath:indexPath]; 

    //Then you change the properties (label, text, color etc..) in your case, the background color 
    theCell.contentView.backgroundColor=[UIColor redColor]; 

    //Deselect the cell so you can see the color change 

    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 

} 

只要确保当你回收的细胞,你认为这个颜色变化。

如果您需要更多信息,请发表评论。

设置为活动行的变量:

int activeRow; 

在构建细胞检查,如果是活动行和背景颜色设置

if (indexPath.row == activeRow) { 
    cell.setMyBackgroundColor = [UIColor myCoolColor]; 
} else { 
    cell.setMyBackgroundColor = [UIColor normalColor]; 
} 

不要忘记设置背景颜色即使在正常情况下,因为它们被重用。

在选择(或者只要是合适的),更新特定的细胞:

NSArray *paths = [NSArray arrayWithObject:indexPath]; 
[self.tableView reloadRowsAtIndexPaths:paths withRowAnimation:YES]; 

我建议这种方法,有可能是导致你的表的刷新事件,你可能不希望丢失背景颜色。如果您只是在选择时直接设置单元格,可能会发生这种情况

+0

+1的答案和最好的解释,非常感谢.. – Shivaay 2014-03-06 10:07:46