2013-02-13 52 views
0

我用下面的方法实现计算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'的值,但我不知道这里应该有什么正确的值。

最终我想要的是在任何内容大小的文本上下都有一致的填充。

任何人都可以帮忙吗?

+0

该值应该是无论您的表视图的宽度(减去一些填充可能)。大约320人的肖像iPhone,对吧? – rdelmar 2013-02-13 07:45:44

+0

只是补充说,它是一个分组tableview,所以宽度不是320我不认为 – conorgriffin 2013-02-13 07:47:50

+0

是的,就像我说的,减去一点填充。当我测量一个时,对我来说看起来像300。 – rdelmar 2013-02-13 07:50:08

回答

0

通过一个消除过程,结果表明幻数是270.0f。 tableView框架的宽度可以从self.tableView.frame.size.width获得。这是320.0f,从这个(等于270.0f)取50.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边缘,单元格内部有多少内部填充,但除非您修改了这两个值中的任何一个,否则它将起作用。

相关问题