iOS自动布局:仅在更新内容后显示单元格

时间:2014-01-30 13:29:02

标签: ios objective-c uitableview autolayout

我使用自动布局并显示带有自定义动态单元格的表格。基本上桌子显示2人之间的聊天。因此,每个单元格的文本消息都不同。

这里的问题是显示第一个单元格,然后在一秒钟内,调整其内容的大小。这显而易见,看起来很糟糕。

请参阅下面的图片,了解它在调整大小之前和之后的外观。

调整大小之前:

enter image description here

调整大小后:

enter image description here

我知道SO上有一个similar question,但它的答案并不能满足需要。我想避免重写layoutSubviews()方法,因为我认为这不是一个足够好的解决方案。

我尝试下面的代码,一旦显示单元格的contentView,就取消隐藏它们。但它不起作用。

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
   // At the begining
    cell.contentView.hidden = NO;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    // Before returning cell
    cell.contentView.hidden = YES;
    return cell;
}

有没有办法延迟显示单元格,直到它们调整大小以适合其内容?

更新:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    chatCell *cell = (chatCell *)[tableView dequeueReusableCellWithIdentifier:CHAT_CELL_IDENTIFIER];

        cell.textString.text = ...;
        cell.textString.frame = ...;
        cell.timeLabel.text = ...;                                             // set timeLabel to display date and time

        cell.userLabel.text = ...;       // set userLabel to display userName

        if (displaying cell where message is sent by user)
        {
            // Set image for sender
            cell.chatCellBackground.image = [[UIImage imageNamed:@"bubbleMine.png"] stretchableImageWithLeftCapWidth:STRETCHED_WIDTH topCapHeight:STRETCHED_HEIGHT];

            cell.chatCellBackground.frame = ...;

        }
        else
        {
            // set bubble for receiver
            cell.chatCellBackground.image = [[UIImage imageNamed:@"bubbleSomeone.png"] stretchableImageWithLeftCapWidth:STRETCHED_WIDTH topCapHeight:STRETCHED_HEIGHT];

            cell.chatCellBackground.frame = ...;
        }
    }

    [cell setNeedsLayout];
    [cell layoutIfNeeded];
    return cell;
}

1 个答案:

答案 0 :(得分:1)

我在自定义UITableViewCell的课程中添加了以下方法。

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat maxTextWidth = [UIScreen mainScreen].bounds.size.width * 0.40;
    self.userLabel.preferredMaxLayoutWidth = maxTextWidth;
    self.chatMessage.preferredMaxLayoutWidth = maxTextWidth;
    self.timeLabel.preferredMaxLayoutWidth = self.timeLabel.frame.size.width;
    [super layoutSubviews];
}

我还发现在

中返回完全正确的细胞高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

方法至关重要。

提示:

  1. 如果任何视图的高度大于预期,则可能计算出的单元格高度大于实际需要的高度。
  2. 如果任何视图垂直缩小或不显示整个内容,则可能计算出的单元格高度小于实际需要的高度。
  3. Yoy可以通过添加/删除您为单元格计算的高度(变量)的常量值来测试高度是否错误。