![](/img/trans.png)
[英]How to change the color of selected row and unselected row in UITableview?
[英]How do I change the color of a UITableView row when it is selected?
我一直在寻找解决方案,但尚未找到可行的方法。 我要做的就是能够更改背景颜色或我选择的UITableView行的图像。
当我选择一行时,我习惯于仅转换视图,但是这次我希望能够更改该行的属性。 我知道我要使用indexPath.row更改哪一行,但是我不知道如何更改行的外观,因为已经调用了cellForRowAtIndexPath方法!
我该怎么做才能改变颜色?
您可以这样做:
- (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];
我建议使用此方法,因为可能会有一些事件导致表刷新,并且您可能不想丢失背景色。 如果仅在选择时直接设置单元格,则可能会发生这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.