A UITableView contains a multi-line UILabel. sizeToFit on the label works the first time, but sizes the label incorrectly once the cell is redrawn
I log info and size the label like this:
NSLog([NSString stringWithFormat:@"before: %@, %f", [item valueForKey:@"item"], itemDescLabel.frame.size.width]);
[itemDescLabel sizeToFit];
NSLog([NSString stringWithFormat:@"after: %@, %f", [item valueForKey:@"item"], itemDescLabel.frame.size.width]);
At first it is correct and logs data like
before: Nachos, 280.000000
after: Nachos, 265.000000
before: Quesadilla, 232.000000
after: Quesadilla, 229.000000
But after scrolling up and down, the labels will obviously be too wide or too narrow, and it logs data like
before: Nachos, 0.000000
after: Nachos, 967.000000
before: Quesadilla, 171.000000
after: Quesadilla, 167.000000
I use the method suggested by Apple for loading a custom UITableViewCell from a nib, like
UITableViewCell *ce开发者_JAVA百科ll = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"ItemCell" owner:self options:nil];
cell = itemCell;
itemCell = nil;
}
UILabel *itemDescLabel = (UILabel *)[cell.contentView viewWithTag:1];
I needed to reset the size of the frame of the UILabel before calling sizeToFit. Cells are reused to save memory, and apparently sizeToFit sometimes gets screwed up when frame.size is not the original one of the label. I have no idea why this is, but it works.
精彩评论