2

I've read through quite a few posts and none of them answer this question. I've created a tableview that populates a list of player names. When the user taps on a name I want the background color of the cell to change to either red, yellow, or green depending on where they are at in the cycle. I am not trying to change the selectionStyle color. The changing of the background color will indicate how difficult of questions each player is going to receive in the game. This it what I've been trying so far. When I debug I can see that didSelectRowAtIndexPath is being hit, but nothing changes. Any Ideas?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Player Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.backgroundColor = [UIColor greenColor];
    UILabel *playerName = (UILabel *)[cell viewWithTag:PLAYER_NAME];

    playerName.backgroundColor = [UIColor redColor];
}
0

1 Answer 1

8

Try:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    cell.backgroundColor = [UIColor greenColor];
    UILabel *playerName = (UILabel *)[cell viewWithTag:PLAYER_NAME];

    playerName.backgroundColor = [UIColor redColor];
}

This should work because you are only going to be asking for a visible cell. The table will return the already visible cell.

You really also need to update some state variable in your data source so if this cell scrolls off and then back into view, you will know to draw the cell again with the proper color.

1
  • Thanks! This worked perfectly! I'm pretty new to iOS and I really appreciate the help. I'll accept this answer when given that chance.
    – Weston
    Jan 26, 2013 at 23:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.