0

I have looked at several questions asking to adjust row height based on cell content. But in my case, I have 10 labels in one cell and each label has fixed width. Labels must wrap the text if not fit to label width. So row height depends on all 10 label's text content. That means I have to calculate height of every label for given text and take maximum height amongst all labels as row height. I have to do this for all rows. This looks to me an insufficient solution. Is there any better solution?

Thanks,

Jignesh

4

2 回答 2

2

您需要在显示单元格之前计算所有高度。之后使用以下命令返回每行的行高:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

要计算文本大小,请使用:

[yourString sizeWithFont:constrainedToSize:lineBreakMode:]
于 2013-05-09T14:54:44.910 回答
1

UITableView要求您实现表格单元格的heightForRowAtIndexPath自定义高度。这是因为UITableView每次重新加载数据时都会计算表格的总高度。如果数据是静态的,您也可以缓存行高计算。

在您的情况下,我建议创建一个代表所有 10 个标签的文本价值的数据模型类,并在该数据模型类上提供一个您可以调用的辅助函数heightForRowAtIndexPath。辅助函数将封装行高计算可能是这样的:

假设您有一个表示行中数据的数据模型类:

@interface MyDataModelClass : NSObject

@property (strong, nonatomic) NSString *label1Text;
@property (strong, nonatomic) NSString *label2Text;
// ... etc

- (CGFloat)calculateLabelHeight;

@end

那么你的calculateLabelHeight方法可能看起来像这样(这显然只是伪代码):

- (CGFloat)calculateLabelHeight {

    CGFloat totalHeight = 0.0;

    // Loop through your label texts calculating the variable sized height for each 
    // and adding some padding in between:

   CGSize variableSize1 = [self.label1Text sizeWithFont:[UIFont systemFontOfSize:12.0] constrainedToSize:CGSizeMake(300, 400) lineBreakMode:NSLineBreakByWordWrapping];

   CGSize variableSize2 = [self.label2Text sizeWithFont:[UIFont systemFontOfSize:12.0] constrainedToSize:CGSizeMake(300, 400) lineBreakMode:NSLineBreakByWordWrapping];

    totalHeight = variableSize1 + padding + variableSize2 + padding; // and so on for all your labels.

    return totalHeight;
}

然后heightForRowAtIndexPath你可以这样做:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

    MyDataModelClass *modelObject = [self.data objectAtIndex:indexPath.row];

    // Assuming model object's label text properties have been set you can do this:

    return modelObject.calculateLabelHeight;
}

我突然想到一个标签中可能有一个长字符串,导致它包裹并可能覆盖第二个标签。在您知道每个标签文本的高度之后,您可能还想为UITableViewCell子类添加一个方法repositionLabels或为您执行此操作的方法。

不幸的是,我认为这是计算单元格高度的唯一方法。有关更多信息,请参阅此 SO 帖子:

IOS:具有自定义 uitableviewcell 的动态高度

于 2013-05-09T15:17:29.723 回答