我使用以下方法实现来计算包含多行文本的UITableViewCell的高度:
- (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条目:
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‘值,但我不知道这里应该是什么值。
最终,我想要的是有一个单元格,有任何内容大小的文本上下一致的填充。
有人能帮上忙吗?
发布于 2013-02-13 16:32:19
通过消除的过程,它的魔数是270.0f。可以从self.tableView.frame.size.width获取tableView帧的宽度。这是320.0f,从这里取50.0f (等于270.0f)似乎可以产生一致的结果。
因此,方法应该如下:
- (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边缘的距离,以及有多少是单元格本身的内部填充,但除非您修改了这两个值中的任何一个,否则它是有效的。
https://stackoverflow.com/questions/14848639
复制相似问题