I have a prototype cell inside my UITableView
which contains a UILabel
. I want to dynamically change the size of the label (and the cell) depending on the size of the text in the label.
I create the prototype cell in cellForRowAtIndexPath
like this:
static NSString *CellIdentifier = @"ProgramDetailCell";
ProgramDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.descriptionLabel.text = self.program.subtitle;
return cell;
Then my ProgramDetailCell
has the following implementation:
@implementation ProgramDetailCell
- (void)layoutSubviews {
[super layoutSubviews];
[self.descriptionLabel sizeToFit];
}
@end
The first time the cell is displayed, layoutSubviews
is called, but the descriptionLabel
does not get resized. However, if I scroll down the table and back up again, the "reused" cell appears with the label correctly resized!
Why does it not work the first time the cell is displayed - and what do I need to do to fix it.
Thanks in advance!
Because when
layoutSubviews
is called yourdescriptionLabel
's text is not set yet. And when you scroll, the text is set. So it is correct now.I suggest you call
sizeToFit
after you set the text.