2

我正在尝试在 UITableViewCells 中创建多行动态 UILabel。我有一个带有“评论”标签的自定义 UITableViewCell。单元格和标签在情节提要中创建。

我可以根据要存储在 UILabel 中的多行数据(使用 heightForRowAtIndexPath)正确计算 UITableViewCells 的高度。但是,我的问题在于实际的 UILabel 内容。UILabel 内容将在表加载时仅显示 1 行数据。但是,一旦包含多行 UILabel 数据的单元格移出屏幕并重新出现在屏幕上,多行数据就会正确显示在具有多行的 UILabel 中。有没有办法解决这个问题,以便多行数据在表加载时正确显示?

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cCell = (CustomCell *)cell;
    MyObject = [myArray objectAtIndex:indexPath.row];

    cCell.commentLabel.frame = CGRectMake(65.0f, 28.0f, 243.0f, 200.0f);
    cCell.commentLabel.text = MyObject.multi_line_text_data;
    cCell.commentLabel.adjustsFontSizeToFitWidth = NO;
    cCell.commentLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    cCell.commentLabel.font = [UIFont systemFontOfSize:13.0];
    cCell.commentLabel.lineBreakMode = NSLineBreakByWordWrapping;
    cCell.commentLabel.numberOfLines = 0;
    [cCell.commentLabel sizeToFit];

}

谢谢!

4

2 回答 2

2

Since you're doing this in the storyboard, you can set the necessary label properties there (lineBreakMode and number of lines). Just give the label a specific width constraint and constraints to the top, bottom, and left sides of the cell. Then, in code use sizeWithFont:constrainedToSize:lineBreakMode: in heightForRowAtIndexPath: to calculate the appropriate height for the cell based on the content of the label -- the label, because of its constraints, will expand along with the cell to the proper size. Something like this:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGSize rowSize = [self.theData[indexPath.row] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(260, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
    return rowSize.height + 30;
}

Here, 260 was the width I gave my label in IB, and the 30 is a fudge factor (determined empirically) to account for padding above and below the label.

于 2013-07-08T01:06:00.207 回答
-1

I met the same problems. Unchecking Autolayout can fix it.

于 2013-12-26T01:35:56.400 回答