【问题标题】:Auto adjust the UITableViewCell height depending on its contents根据内容自动调整 UITableViewCell 高度
【发布时间】:2010-10-14 10:09:54
【问题描述】:

我想根据单元格的内容调整单元格的高度。我知道 UITableViewDelegate 可以让你实现

- (CGFloat) tableView: (UITableView *) tableView 
              heightForRowAtIndexPath: (NSIndexPath *) indexPath {
    return someHeight;
}

但我不想硬编码高度。有没有办法动态地做到这一点?

【问题讨论】:

  • 当然有。但是如何做到这一点在很大程度上取决于你想做什么。如果要根据图像更改单元格高度,这非常简单,如果要使单元格高度取决于字符串中的换行符,则需要进行更多计算。那你想做什么?
  • 好吧,我有一个自定义单元格,它接受一个 UILabel 或一个 UIImageView。就像你说的,根据图像的高度调整高度非常简单。但是我如何知道 UILabel 需要多少空间呢?

标签: iphone objective-c uitableview


【解决方案1】:

您必须在计算行内容高度的方法中输入一些代码。您需要放置的确切代码完全取决于您要显示的内容类型。

例如,如果您要显示可能跨越多行的文本内容,您可能最终会使用 NSString 的 sizeWithFont: 系列方法之一。

【讨论】:

    【解决方案2】:

    如果你想让你的行有不同的高度,你必须计算每一行的高度。

    我遇到过这样的问题。我根据从 json 字符串解析的内容计算了行的高度。这就是我所做的。

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        // parse json
        id qWeiboContent = [self.array objectAtIndex:indexPath.row];
    
        float totalContentHeight;
        QWeiboContentModel *model = [self getQWeiboContentFromJSON:qWeiboContent];
        QWeiboContentModel *subModel = nil;
    
        totalContentHeight += model.forOrComment.heightValue;   // comment text view's height
        totalContentHeight += model.content.heightValue;        // content text view's height
        totalContentHeight += 21 * 2;                           // 21 is height of a label
        totalContentHeight += model.imageUrl.heightValue;
        totalContentHeight += CELL_CONTENT_MARGIN;
    
        if ([model.type isEqualToString:REPOSTED]) {
    
            id qWeiboSource = [qWeiboContent objectForKey:@"source"];
            subModel = [self getQWeiboContentFromJSON:qWeiboSource];
            model.source = subModel;
    
            totalContentHeight += subModel.forOrComment.heightValue;    
            totalContentHeight += subModel.content.heightValue;         
            totalContentHeight += 21 * 2;                              
            totalContentHeight += subModel.imageUrl.heightValue;
            totalContentHeight += CELL_CONTENT_MARGIN;
        }
    
        if (self.arrayQQWeibo == nil) {
    
            self.arrayQQWeibo = [[NSMutableArray alloc]init];
        }
        [self.arrayQQWeibo addObject:model];
    
        return totalContentHeight;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-21
      • 2011-03-22
      • 1970-01-01
      • 2012-05-21
      • 2015-08-02
      • 1970-01-01
      • 2012-08-03
      • 2010-12-18
      相关资源
      最近更新 更多