定制UITableViewCell的高度

如何根据其中的内容数量来扩展UITableViewCells? 在我的单元格中,我使用了代表论坛的3个标签。 标签被命名为“别名”,“date”和“评论”。 第三个标签评论,可以是任何数量的大小。 因此,我的单元格需要dynamic取决于“注释”标签的大小。 以下是我的相关代码:

- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"ForumthreadCell"; UITableViewCell *cell = [pTableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } Feedback *item = [self.items objectAtIndex:indexPath.row]; UILabel *aliasLabel = (UILabel *)[cell viewWithTag:1]; UILabel *commentLabel = (UILabel *)[cell viewWithTag:2]; UILabel *dateLabel = (UILabel *)[cell viewWithTag:3]; [aliasLabel setText:item.alias]; [commentLabel setText:item.comment]; [dateLabel setText:[self.dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:(double)item.time]]]; commentLabel.numberOfLines = 0; [commentLabel sizeToFit]; CGSize textHeight = [commentLabel.text sizeWithFont:commentLabel.font constrainedToSize:CGSizeMake(maxWidth, lineHeight * commentLabel.numberOfLines)lineBreakMode:UILineBreakModeWordWrap]; return cell; } 

正如你所看到的,我用textHeight设置了commentsLabel的高度。 但是现在我该怎么办呢? 如果我知道标签的高度,如何根据commentLabel的高度来设置单元的高度? 请根据我的代码给出代码示例。 我想我应该使用下面的方法,但我不知道如何做到这一点:

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

使用此方法获取文本的文本高度

 -(CGFloat)getLabelHeightForText:(NSString *)text andWidth:(CGFloat)labelWidth { CGSize maximumSize = CGSizeMake(labelWidth, 10000); //provide appropriate font and font size CGSize labelHeighSize = [text sizeWithFont: [UIFont fontWithName:@"Trebuchet MS" size:13.0f] constrainedToSize:maximumSize lineBreakMode:UILineBreakModeTailTruncation]; return labelHeighSize.height; } 

此方法将返回您传递的文本的高度。 在你的class级中添加这个方法。 并使用tableView:heightForRowAtIndexPath:委托方法来设置每个单元格的高度

 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { Feedback *item = [self.items objectAtIndex:indexPath.row]; CGFloat textHeight = [self getLabelHeightForText:item.comment andWidth:162];//give your label width here return textHeight; } 

我认为这可以解决问题。

你可以在你的实现中创buildLabel声明:

 @implementation pTableView { UILabel *aliasLabel; } 

然后在行高中,可以使用默认高度(44)+ aliasLabel.Height

 return 44 + aliasLabel.frame.size.height; 

那么如果你需要区分你的表中的标签

 aliasLabel.tag = indexpath.row