自定义UITableViewCell的高度

use*_*618 0 uitableview ios

如何根据UITableViewCells中的内容量来扩展它们?在我的单元格中,我使用3个代表论坛的标签.标签名为"别名","日期"和"评论".第三个标签注释,可以是任意数量的大小.因此,我的单元格需要动态变化,具体取决于"注释"标签的大小.以下是我的相关代码:

- (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;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我使用textHeight设置commentsLabel的高度.但是从现在开始我该怎么办?如果我知道标签的高度,我如何根据commentLabel的高度设置Cell的高度?请根据我的代码提供代码示例.我想我应该使用以下方法,但我不知道该怎么做:

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

}
Run Code Online (Sandbox Code Playgroud)

Gur*_*uru 6

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

-(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;
}
Run Code Online (Sandbox Code Playgroud)

此方法将返回您传递的文本的高度.在您的课程中添加此方法.并使用 tableView:heightForRowAtIndexPath: delegate方法设置每个单元格的高度

-(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;
}    
Run Code Online (Sandbox Code Playgroud)

我认为这可以解决问题.