【问题标题】:Wrong UITableViewCell height with UITableViewAutomaticDimensionUITableViewAutomaticDimension 的 UITableViewCell 高度错误
【发布时间】:2015-02-07 14:21:17
【问题描述】:

我制作了带有 2 个多行标签的自定义单元格,并将这些标签固定到所有侧面。在 iOS >= 8-tableView:heightForRowAtIndexPath: 中,我返回 UITableViewAutomaticDimension。但是当表格视图出现时,单元格高度大于应有的高度。在我向下滚动然后向上滚动后,单元格采用正常高度。如何解决此问题?

高度代码:

   - (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 uitableview autolayout


    【解决方案1】:

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

    【讨论】:

    • 谢谢,这解决了我的问题。不确定我是否理解它为什么会修复它,但我确信在对该主题进行更多研究后它会来找我。再次感谢!
    • 我保留了estimatedRowHeight 原样,在有问题的UILabel 上添加了preferredMaxLayoutWidth,然后设置了AttributeString 并且它起作用了。为你 +1!
    【解决方案2】:

    我通过将多行标签的“text”属性设置为“nil”解决了这个问题:

    override func prepareForReuse() {
        _label.text = nil
    }
    

    还应正确设置表格属性“estimatedRowHeight”和“rowHeight”:

    _tableView.estimatedRowHeight = 44
    _tableView.rowHeight = UITableViewAutomaticDimension
    

    【讨论】:

    • 太棒了!完美运行(iOS9)
    【解决方案3】:
    如果标签通过顶边底边与不同标签对齐,

    Automatic dimension 不适用于某些 UILabel。只要确保你没有这样的对齐方式。

    【讨论】:

      【解决方案4】:

      在 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 的直观指南

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多