user546719
user546719

Reputation:

UITableViewCell is displayed incorrectly the first time

I'm toggling between different cell backgrounds (white and lightgray) and font properties (bold and normal) with the following code after cell creation or reuse:

- (UITableViewCell *)tableView:(UITableView *)tableView 
    cellForRowAtIndexPath:(NSIndexPath *)indexPath  {
...

 UIView* cellBackgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
 UIFont *font;
 if ([[userModel suspended] boolValue]) {
   [cellBackgroundView setBackgroundColor:[UIColor lightGrayColor]];
   font = [UIFont italicSystemFontOfSize:[[[cell textLabel] font] pointSize]];

 } else {
   [cellBackgroundView setBackgroundColor:[UIColor whiteColor]];
   font = [UIFont boldSystemFontOfSize:[[[cell textLabel] font] pointSize]];
 }
 [cell setBackgroundView:cellBackgroundView];  
 [[cell textLabel] setFont:font];

 [[cell textLabel] setBackgroundColor:[UIColor clearColor]];
 [[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]];
 [[cell textLabel] setText:[NSString stringWithFormat:@"%@, %@", 
                            [userModel familyName], [userModel givenName]]];
 [[cell detailTextLabel] setText:[userModel userName]];

return cell;
}

The problem is that if a cell that needs to be lightgray and italic is on the first set of cells displayed after loading, its background appears lightgray (correctly) but its font is normal (wrong).

If I scroll down and have the cell redisplayed, then it displays as expected.

Thanks, Jorge

Upvotes: 1

Views: 257

Answers (2)

mackworth
mackworth

Reputation: 5953

In the line

font = [UIFont italicSystemFontOfSize:[[[cell textLabel] font] pointSize]]

you are assuming that the cell textLabel already exists and has a correct font. I would NSLog the font just before that call. Also why not just specify the fontsize here: font = [UIFont italicSystemFontOfSize:12.0]

Upvotes: 1

Alex
Alex

Reputation: 8991

Is there a chance that the boolean returned by [[userModel suspended] boolValue] is false at the time when the first group of cells are created?

Upvotes: 0

Related Questions