首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >分组UITableViewCell的heightForRowAtIndexPath

分组UITableViewCell的heightForRowAtIndexPath
EN

Stack Overflow用户
提问于 2013-02-13 15:42:09
回答 1查看 292关注 0票数 0

我使用以下方法实现来计算包含多行文本的UITableViewCell的高度:

代码语言:javascript
复制
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  if (indexPath.section == 1 && indexPath.row == 1) {
    NSDictionary *fields = self.messageDetailsDictionary[@"fields"];
    NSString *cellText = fields[@"message_detail"];
    UIFont *cellFont = [UIFont systemFontOfSize:14.0];
    CGSize constraintSize = CGSizeMake(250.0f, MAXFLOAT);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];

    return labelSize.height + 20;

  } else {

    return tableView.rowHeight;  

  }

}

为了完整起见,下面是该单元格的cellForRowAtIndexPath条目:

代码语言:javascript
复制
  UITableViewCell *cell = [[UITableViewCell new] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DetailCell"];
  if (cell == nil) {
    cell = [[UITableViewCell new] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DetailCell"];
  }
  cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
  cell.textLabel.font = [UIFont systemFontOfSize:14.0];
  NSDictionary *fields = self.messageDetailsDictionary[@"fields"];
  cell.textLabel.numberOfLines = 0; // This means multiline
  cell.textLabel.text = fields[@"message_detail"];

  return cell;

UITableViewCell位于分组的UITableView中,这一点很重要,因为它会影响单元格的宽度。

这在某种程度上是有效的,它计算的单元格高度足以容纳正在输入的文本,但它似乎有点太大了,因为单元格的顶部和底部有一点太多的空间。这取决于文本的数量,所以我不认为它与return labelSize.height + 20;语句有关。我怀疑这是因为我在CGSizeMake中使用的'250.0f‘值,但我不知道这里应该是什么值。

最终,我想要的是有一个单元格,有任何内容大小的文本上下一致的填充。

有人能帮上忙吗?

EN

回答 1

Stack Overflow用户

发布于 2013-02-13 16:32:19

通过消除的过程,它的魔数是270.0f。可以从self.tableView.frame.size.width获取tableView帧的宽度。这是320.0f,从这里取50.0f (等于270.0f)似乎可以产生一致的结果。

因此,方法应该如下:

代码语言:javascript
复制
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

  if (indexPath.section == 1 && indexPath.row == 1) {

    NSDictionary *fields = self.messageDetailsDictionary[@"fields"];
    NSString *cellText = fields[@"message_detail"];
    UIFont *cellFont = [UIFont systemFontOfSize:14.0];
    CGSize constraintSize = CGSizeMake(self.tableView.frame.size.width - 50.0f, MAXFLOAT);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];

    return labelSize.height + 20.0f;

  } else {

    return tableView.rowHeight;  

  }

}

我不确定为什么50.0f是正确的值,因为我不确定50.0f中有多少是从单元格边界到tableView边缘的距离,以及有多少是单元格本身的内部填充,但除非您修改了这两个值中的任何一个,否则它是有效的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14848639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档