简体   繁体   中英

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

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]

在创建第一组单元格时,[[userModel暂停] boolValue]返回的布尔值是否有可能为假?

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