简体   繁体   中英

Changing the background colour of tableview cell in iOS7

I'm having an issue that's appeared since upgrading to iOS7 in which when I try to change the background colour of a specific tableview cell, it doesn't colour the correct cells (usually the specified ones in addition to other ones). As you can see from my code below, I define the type that I want to be highlighted and then change the colour. It worked perfectly prior to the iOS upgrade so I'm not exactly sure what change has been made that's causing this:

Quick edit: also, when I scroll down the tableview and then back up, it colours more cells that weren't coloured when the tableview controller first loads (if that helps at all).

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString* type=[[self.HandPointer.player_hand objectAtIndex:indexPath.row]cardType];
    if ([type isEqualToString:@"ace"]){
        cell.backgroundColor = [UIColor colorWithRed:0.81 green:0.91 blue:0.81 alpha:1.0];
    }
}

I think doing cell customization in tableView: cellForRowAtIndexPath: method is better. In this method,

if ([type isEqualToString:@"ace"])
{
    cell.backgroundColor = [UIColor aceColor];
}
else // this else is important. If you add this, scrolling works fine.
{
    cell.backgroundColor = [UIColor otherCellColor];
}

You likely have a single re-usable cell style. Consider having a re-usable cell style for your aces, and one for all others. Set the background color in cellForRowAtIndexPath, not willDisplayCell.

pseudo-code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
.
.
. 
 NSString* type=[[self.HandPointer.player_hand objectAtIndex:indexPath.row]cardType];
 if ([type isEqualToString:@"ace"]){
 {
  // load a cell with the background color desired
  cell = 
  cell.backgroundColor = 
  .
  .
  .
  return (cell);
 }

 // else a normal cell
 cell = 
 .
 .
 .
}

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