错误的 UITableViewCell 高度与 UITableViewAutomaticDimension

Wrong UITableViewCell height with UITableViewAutomaticDimension

我制作了带有 2 个多行标签的自定义单元格,并将此标签固定在所有边上。当在 -tableView:heightForRowAtIndexPath: for iOS >= 8 I return UITableViewAutomaticDimension.但是当 table 视图出现时,单元格高度比应有的要大。在我向下滚动然后向上滚动后,单元格采用正常高度。如何解决此问题?

身高代码:

   - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
        return UITableViewAutomaticDimension;
    }

    static CCTopicTableViewCell *cell;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cell = [tableView dequeueReusableCellWithIdentifier:@"topicCellIdentifier"];
    });
    cell.topic = [self.topics topicAtIndexPath:indexPath];

    cell.bounds = CGRectMake(0, 0, CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(cell.bounds));

    [cell setNeedsLayout];
    [cell layoutIfNeeded];

    CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return size.height + 1;
}

结果:

滚动后:

当我没有为 iOS 8 设置 tableView 的 estimatedRowHeight 并且每次为多行标签设置文本时更新 preferredMaxLayoutWidth 时问题就消失了

Automatic dimension 对于某些 UILabel 来说效果不佳,如果该标签通过 top edgesbottom edges 与不同的标签对齐。只要确保你没有这样的对齐方式。

在 viewDidLoad() 方法或 viewWillAppear() 中设置自动维度(两个代码在同一位置)

    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.estimatedRowHeight = 160.0;//(Maximum Height that should be assigned to your cell)

访问 Using Auto Layout in UITableView for dynamic cell layouts & variable row heights iOS 7 和 iOS 8

的直观指南

我通过将多行标签的 "text" 属性 设置为 "nil":

解决了这个问题
override func prepareForReuse() {
    _label.text = nil
}

另外 table 属性 "estimatedRowHeight" 和 "rowHeight" 应该正确设置:

_tableView.estimatedRowHeight = 44
_tableView.rowHeight = UITableViewAutomaticDimension