I had the same experience in one of my projects.
Why is this happening?
A cell designed in a storyboard with some width for some device. For example, 400 pixels. For example, your label has the same width. When it loads from the storyboard, it has a width of 400 pixels.
Here is the problem:
tableView:heightForRowAtIndexPath: called before the location of the cells it is viewing.
So, he calculated the height for the label and cell with a width of 400 pixels. But you start the device with a screen, for example, 320 pixels. And this automatically calculated height is incorrect. Just because the layoutSubviews cell layoutSubviews happens after tableView:heightForRowAtIndexPath: Even if you set the preferredMaxLayoutWidth for your label manually in layoutSubviews , this will not help.
My decision:
1) Subclass UITableView and override dequeueReusableCellWithIdentifier:forIndexPath: Set the cell width equal to the width of the table and the power cell.
- (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [super dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath]; CGRect cellFrame = cell.frame; cellFrame.size.width = self.frame.size.width; cell.frame = cellFrame; [cell layoutIfNeeded]; return cell; }
2) Subclass of UITableViewCell . Set preferredMaxLayoutWidth manually for your labels in layoutSubviews . Also you need to manually layout the contentView , because it is not automatically the layout after changing the cell border (I do not know why, but it is)
- (void)layoutSubviews { [super layoutSubviews]; [self.contentView layoutIfNeeded]; self.yourLongTextLabel.preferredMaxLayoutWidth = self.yourLongTextLabel.width; }
Vitaliy Gozhenko Sep 28 '15 at 21:54 2015-09-28 21:54
source share