UITableViewCell needs reloadData() to resize to correct height

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

I have the a custom tableview cell with applied constraints but the first time the table is displayed the row height is not resized properly unless new cells are created, is there a way to do this without calling reloadData again?

回答1:

Yes. This is actually an issue with self-sizing that you need to work around until it is fixed.

The problem is that when a cell is instantiated, its initial width is based on the storyboard width. Since this is different from the tableView width, the initial layout incorrectly determines how many lines the content actually would require.

This is why the content isn't sized properly the first time, but appears correctly once you (reload the data, or) scroll the cell off-screen, then on-screen.

You can work around this by ensuring the cell's width matches the tableView width. Your initial layout will then be correct, eliminating the need to reload the tableView:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {     TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];      [cell adjustSizeToMatchWidth:CGRectGetWidth(self.tableView.frame)];      [self configureCell:cell forRowAtIndexPath:indexPath];      return cell; } 

In TableViewCell.m:

- (void)adjustSizeToMatchWidth:(CGFloat)width {     // Workaround for visible cells not laid out properly since their layout was     // based on a different (initial) width from the tableView.      CGRect rect = self.frame;     rect.size.width = width;     self.frame = rect;      // Workaround for initial cell height less than auto layout required height.      rect = self.contentView.bounds;     rect.size.height = 99999.0;     rect.size.width = 99999.0;     self.contentView.bounds = rect; } 

I'd also recommend checking out smileyborg's excellent answer about self-sizing cells, along with his sample code. It's what tipped me off to the solution, when I bumped into the same issue you are having.

Update:

configureCell:forRowAtIndexPath: is an approach Apple uses in its sample code. When you have more than one tableViewController, it is common to subclass it, and break out the controller-specific cellForRowAtIndexPath: code within each view controller. The superclass handles the common code (such as dequeuing cells) then calls the subclass so it can configure the cell's views (which would vary from controller to controller). If you're not using subclassing, just replace that line with the specific code to set your cell's (custom) properties:

    cell.textLabel.text = ...;     cell.detailTextLabel.text = ...; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!