iphoneuitableviewselectbackground

How do I change the color of a UITableView row when it is selected?


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 transitioning 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?


Solution

  • 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.