iOS自动布局:仅在更新内容后显示单元格
我使用自动布局并显示带有自定义动态单元格的表格。 基本上桌子显示2人之间的聊天。 因此,每个单元格的文本消息都不同。
这里的问题是显示第一个单元格,然后在一秒钟内,调整其内容的大小。 这显而易见,看起来很糟糕。
请参阅下面的图片,了解它在resize之前和之后的外观。
在resize之前:
resize后:
我知道在SO上有一个类似的问题 ,但它的答案并不能满足需要。 我想避免重写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; }
有没有办法延迟显示单元格,直到它们被resize以适应其内容?
更新:
- (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; }
我在自定义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
方法至关重要。
提示:
- 如果任何视图的高度大于预期,则可能计算的单元格高度大于实际需要的高度。
- 如果任何视图垂直缩小或不显示整个内容,则可能计算的单元格高度小于实际需要的高度。
Yoy可以通过添加/删除您为单元格计算的高度(变量)的常量值来测试高度是否错误。