1

I'm loading up a table view where each table cell has some left indentation (think message threads/replies) and also contains a label which is of dynamic height (the contents of the reply). I'm using AutoLayout so the UILabel sizes itself. In order to implement the indentation for each UITableViewCell I followed the advice of people here on SO to override layoutSubviews for my UITableViewCell so it looks like this:

- (void)layoutSubviews
{
    [super layoutSubviews];

    float indentPoints = self.indentationLevel * self.indentationWidth;

    self.contentView.frame = CGRectMake(indentPoints,
        self.contentView.frame.origin.y,
        self.contentView.frame.size.width - indentPoints,
        self.contentView.frame.size.height);
}

What's happening now though is sometimes the UILabel text will be cut-off at the bottom. It seems to me that the UILabel is working off the old frame size when calculating it's appropriate height and drawing itself (since it is dynamic) not the new frame size which has indentation - with indentation, there is less width available for the same text, so it should know it needs to be taller.

If I remove this indentation and comment out my override of layoutSubviews or if I put the call to [super layoutSubviews] at the end, rather than the beginning, the text is no longer cut-off, but I lose my indentation.

What I want is for my UITableViewCell to be indented appropriately and for my dynamic UILabel to recognise the new frame size and draw without any cut-off. I've tried putting in calls to layoutIfNeeded in various places for my UILabel without success.

4

2 回答 2

0

您需要使用以下方法预先计算 UILabel 的大小:

CGSize size = [str sizeWithFont:label.font constrainedToSize:CGSizeMake(label.bounds.size.width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];

使用它来调整您的单元格大小。在您的 tableview 数据源 heightForRowAtIndexPath 中执行此操作可能会更好

于 2013-10-28T03:00:35.320 回答
0

事实证明,这个问题的根本原因与以下 Stack Overflow 帖子相同:UILabel not wrapping text有时(自动布局)

使用公认的解决方案(在 layoutSubViews 中设置 PreferredMaxLayoutWidth)为我解决了这个问题。

于 2013-10-28T07:06:49.647 回答