iOS 7中的自动调整表格视图单元格

时间:2013-10-27 21:14:55

标签: ios objective-c

我知道这个问题已被多次询问,但我很难找到正确的iOS7实现。

我有一个tableview,它由一个从我的服务器检索JSON数据的数组填充。这些数据可以是任何长度。现在我只能得到1或2行,仅此而已。

有没有人对正确的heightForRowAtIndexPath实施有任何提示?

由于

编辑(当前代码):

-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
// Retrieve the line for this index (from JSON)

NSString *line = [myArray objectAtIndex:indexPath.row];
CGSize size = CGSizeZero;

size = [line boundingRectWithSize: (CGSize){640, CGFLOAT_MAX} options: NSStringDrawingUsesLineFragmentOrigin
                             attributes: @{ NSFontAttributeName: [UIFont systemFontOfSize:18]} context: nil].size;
return ceilf(size.height);
}

1 个答案:

答案 0 :(得分:0)

您只需要正确实施heightForRowAtIndexPath,就像这样

-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
    // Retrieve the line for this index (from JSON)
    NSString* line = ...

    // Measure it with UIKit
    // font is a UIFont* and should be prepared once when the view initialized
    // cellSize is a CGSize like (320, 10000), where 320 is the width of the cell, 10000 means we want it as high as needed
    CGSize sz = [line sizeWithFont:font constrainedToSize:cellSize lineBreakMode: NSLineBreakByWordWrapping];

    return sz.height;
}

对于cellForRowAtIndexPath,只需使标签适合整个单元格。

有关NSString UIKit Additions的更多信息,请参阅this。请注意,方法[sizeWithFont:constrainedToSize:lineBreakMode:]在iOS 7中已弃用,已被其他方法替换,但我不确定如何使用它:)