gpt4 book ai didi

ios - 自定义 UITableViewCell 的高度

转载 作者:行者123 更新时间:2023-11-28 18:24:28 24 4
gpt4 key购买 nike

如何根据其中的内容量缩放 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com