我用下面的方法实现计算UITableViewCell
这是一个包含多行文本的高度:heightForRowAtIndexPath为分组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'的值,但我不知道这里应该有什么正确的值。
最终我想要的是在任何内容大小的文本上下都有一致的填充。
任何人都可以帮忙吗?
该值应该是无论您的表视图的宽度(减去一些填充可能)。大约320人的肖像iPhone,对吧? – rdelmar 2013-02-13 07:45:44
只是补充说,它是一个分组tableview,所以宽度不是320我不认为 – conorgriffin 2013-02-13 07:47:50
是的,就像我说的,减去一点填充。当我测量一个时,对我来说看起来像300。 – rdelmar 2013-02-13 07:50:08