I've looked around for answers to this but have yet to find one that works. All I want to do is to be able to change the background color, or image of the UITableView row that I select.
I am used to just tran开发者_JS百科sitioning views when you I select a row, but this time I want to be able to change that rows properties. I know which row I want to change, with indexPath.row, but I don't know how I would go about changing how the row looks because the cellForRowAtIndexPath method has already been called!
What can I do to change the color?
You would do it like this:
- (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];
}
Just make sure you consider this color change when you recycle cells.
If you need more info just post a comment.
Set a variable to the active row:
int activeRow;
When building the cell check if it's the active row and set the background color
if (indexPath.row == activeRow) {
cell.setMyBackgroundColor = [UIColor myCoolColor];
} else {
cell.setMyBackgroundColor = [UIColor normalColor];
}
Don't forget to set the background color even on the normal case, since they are reused.
On selection (or whenever is appropriate), update that particular cell:
NSArray *paths = [NSArray arrayWithObject:indexPath];
[self.tableView reloadRowsAtIndexPaths:paths withRowAnimation:YES];
I would suggest this method as there may be events that cause the refresh of your table, and you may not want to lose the background color. This could happen if you just set the cell directly on selection.
精彩评论