简体   繁体   中英

UITableView - Change cell color on tap

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];
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM