ios - 自定义 UITableViewCell 的高度

标签 ios uitableview

如何根据其中的内容量缩放 UITableViewCells?在我的单元格中,我使用 3 个标签来代表一个论坛。这些标签被命名为“别名”、“日期”和“评论”。第三个label comments,可以任意大小。因此,我的单元格需要根据“评论”标签的大小动态变化。下面是我的相关代码:

- (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 的高度设置 Cell 的高度?请根据我的代码给出代码示例。我想我应该使用以下方法,但我不确定该怎么做:

- (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;
}

此方法将返回您传递的文本的高度。在你的类中添加这个方法。并使用 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;
}    

我认为这可以解决问题。

关于ios - 自定义 UITableViewCell 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13123540/

相关文章:

ios - 在 Swift 中发送应用程序电子邮件

ios - Apple Mach-O Linker Error 主可执行文件的隐式输入/启动

objective-c - 如何将自定义单元格添加到 UITableView 的底部?

objective-c - 如何为同一个表格中的不同单元格设置不同的UITableViewCell Style?

ios - 阴影不符合 UITableViewCell 中 View 的形状

ios - 使用prepareForSegue从 TableView 详细信息披露中传递零数据

ios - ios设备之间的同步

ios - DateFormatter 返回错误的时间

Swift - Tableviewcell删除图标自定义

arrays - Swift tableview 单元格重用问题