【问题标题】:Dynamic UITableViewCell with insertRowAtIndexPath带有 insertRowAtIndexPath 的动态 UITableViewCell
【发布时间】:2014-11-16 18:05:40
【问题描述】:

我正在尝试设计一个 UITableView,我需要在其中插入一行,其高度(自定义 UITableViewCell 高度)将取决于其 UILabel 字符串的长度。

我跟随 Ray Wenderlich 的 this tutorial 来调整 uitableview 单元格的高度相对于它的 UILabel 高度。但是当我使用 insertRowAtIndexPath 使用自定义 UITableViewCell 插入一行时,

dispatch_once(&onceToken, ^{
    sizingCell = [self.tableView dequeueReusableCellWithIdentifier:RWBasicCellIdentifier];
  });

将确保一行只插入一次而不是多次。

如何插入可变高度的RowAtIndexPath?

这是我的 heightForRowAtIndexPath

ChattingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChattingCellId2"];
        CGRect messageLabelRect = [cell.labelMessage.attributedText boundingRectWithSize:(CGSize){cell.labelMessage.frame.size.width, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin context:nil];
        cell.labelMessage.frame = CGRectMake(cell.labelMessage.frame.origin.x, cell.labelMessage.frame.origin.y, cell.labelMessage.frame.size.width, messageLabelRect.size.height);
        [cell.labelMessage sizeThatFits:CGSizeMake(cell.labelMessage.frame.size.width, messageLabelRect.size.height)];
        float height = cell.labelMessage.frame.origin.y + cell.labelMessage.frame.size.height + cell.labelSent.frame.size.height + 10;
        [cell prepareForReuse]; //here your cell would normally be returned for cellForRowAtIndexPath, except we just mark it for reuse, we have the height we need
        return height;

【问题讨论】:

  • 发布的代码与您的问题有什么关系?使用 insertRowAtIndexPath 与您的问题无关。实施heightForRowAtIndexPath。这将处理任何行,无论它如何添加到表中。
  • 我了解@rmaddy .. 我知道数据源和委托方法.. 但是如何使用 heightForRowAtIndexPath 仅更改一个单元格的 UITableViewHeight?
  • 我的意思是 uitableviewcell 高度
  • heightForRowAtIndexPath 用于所有行,而不仅仅是一个。根据给定索引路径的数据进行计算。
  • @rmaddy 我在我的问题中添加了我的 heightForRowAtIndexPath 代码

标签: ios objective-c uitableview


【解决方案1】:

您还应该在表格视图控制器中实现heightForRowAtIndexPath。 当您调用insertRowAtIndexPath 时,首先调用heightForRowAtIndexPath,然后调用cellForRowAtIndexPath。 在heightForRowAtIndexPath 中,您必须确定新单元格的高度,假设您使用的是自动布局,因此您可以设置 单元格的frame.size.width 并通过调用setNeedsLayoutlayoutIfNeeded 强制布局单元格,然后您就有了自动布局计算的高度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 2015-03-07
    相关资源
    最近更新 更多