Ios 如何处理单元格中的动态文本高度?

Ios 如何处理单元格中的动态文本高度?,ios,objective-c,uitableview,Ios,Objective C,Uitableview,我在UITableViewCell中有一个UILabel。我没有使用自动布局,而是手动创建和添加视图。 UILabel可以包含可变数量的文本,因此我在tableview委托中实现heightForRowAtIndexPath - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { TableCellWithDocument *cell = (Table

我在UITableViewCell中有一个UILabel。我没有使用自动布局,而是手动创建和添加视图。 UILabel可以包含可变数量的文本,因此我在tableview委托中实现heightForRowAtIndexPath

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   TableCellWithDocument *cell = (TableCellWithDocument*)[self tableView: tableView cellForRowAtIndexPath: indexPath];
   NSLog(@"Cell frame: %@", NSStringFromCGRect(cell.frame));
   return [cell heightForCellForWidth: cell.frame.size.width];
我遇到的问题是,当调用此委托方法时,单元格的帧大小不正确。它只返回默认值320x44。 因此,当我试图计算标签大小时,我的单元格宽度和单元格高度都是错误的

在我的子类TableCellWithDocument类中,我可以覆盖LayoutSubView并获得正确的单元格宽度,但这已经太晚了,因为已经调用了HeightForRowatinedExath


我应该如何处理这个问题?

您正在以递归方式进行处理。如果仔细调试代码,您会发现heightForRowAtIndexPath首先被调用以估计单元格高度,而cellForRowAtIndexPath稍后被调用

理想情况下,在heightforrowatinexpath中,您应该获取所有数据源内容,并估计其大小。cellForRowAtIndexPath应该能够使用此高度设置单元格内容

例如,如果要显示一些文本,可以使用[UILabel sizeThatFits]或[NSString SizeWhont]方法估计cell.textLabel大小,依此类推


请记住,没有答案是正确的答案,您必须根据自己的数据进行调整-无论是字符串、图像还是其他数据。必须由数据大小而不是控件的大小来决定从heightForRowAtIndexPath返回的内容。

尝试在HeightForRowAtexPath中执行此操作

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   TableCellWithDocument *cell = (TableCellWithDocument*)[self tableView: tableView cellForRowAtIndexPath: indexPath];
   NSLog(@"Cell frame: %@", NSStringFromCGRect(cell.frame));
   return [cell heightForCellForWidth: cell.frame.size.width];
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize size = [text sizeWithFont:[UIFont fontWithName: @"YourFont" size:24.0];
                   constrainedToSize:CGSizeMake(kMessageTextWidth, CGFLOAT_MAX)
                       lineBreakMode:NSLineBreakByWordWrapping];


    return MAX(size.height + 17.0f);
}

iOS7.0以后版本不推荐使用sizeWithFont方法。您将需要改用boundingrectize:options:attributes:context:method。