UITableViewCell needs reloadData() to resize to correct height

前端 未结 1 1977
孤城傲影
孤城傲影 2021-01-20 21:06

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

相关标签:
1条回答
  • 2021-01-20 21:20

    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 = ...;
    
    0 讨论(0)
提交回复
热议问题