灵活的高度表查看某些字符串长度的单元格

时间:2012-02-28 23:17:16

标签: iphone ios uitableview

晚上,

我有几个UITableViewCell根据其中包含的文本在高度上动态扩展,但似乎一旦输入了一定数量的字符(虽然我还没有测试过,所以我不确定它是否确切因此,高度计算不正确。

以下是我的代码的相关部分,其中包含导致问题的示例字符串,故意截断为1000个字符(用户可以键入的字段的最大长度):

Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.

Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it.[1] Objective-C is the primary language used for Apple's Cocoa API, and it was originally the main language on NeXT's NeXTSTEP operating system. Generic Objective-C programs that do not use these libraries can also be compiled for any system supported by gcc or Clang.

Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.

Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it.[1] Objective-C is the primary language used for Apple's Cocoa API, and it was originally the main language on NeXT's NeXTSTEP operating system. Generic Objective-C programs that do no

这来自我的cellForRowAtIndexPath: ..

cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
cell.detailTextLabel.font = [UIFont systemFontOfSize:15];
cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.detailTextLabel.numberOfLines = 0;

然后我使用以下方法计算单元格高度:

- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath {

NSString *cellLabel;
NSString *cellText;

if (indexPath.section == 0) {
    // This returns a small string such as 'Note'
    cellLabel = [generalDetailsCellsArray objectAtIndex:indexPath.row];
    // This returns the example string posted in the above block
    cellText = [generalDetailsValuesArray objectAtIndex:indexPath.row];
}

--- snip ---

CGSize constraint = CGSizeMake(300.0f, 20000.0f);

CGSize labelSize = [cellLabel sizeWithFont:[UIFont boldSystemFontOfSize:15] constrainedToSize:constraint];
CGSize textSize = [cellText sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraint];

return (labelSize.height + textSize.height) + 12;
}

任何人都可以看到任何明显的混乱吗?

提前致谢。

2 个答案:

答案 0 :(得分:0)

听起来你还没有找到确切的错误情况。在担心计算行高的代码之前,请通过示例准确定义问题。你可能是正确的,因为你在某种程度上算错了,但这并不是第一次在获得必要的信息来重新创建问题之后,你会发现它是另一个问题。

答案 1 :(得分:0)

如果其他人遇到这个问题,请不要像我那样犯同样的错误!

CGSize constraint = CGSizeMake(300.0f, 20000.0f)应为CGSize constraint = CGSizeMake(280.0f, 20000.0f),我没有考虑到单元格内的单元格填充,因此我计算的标签宽度比绘制到单元格时的标签宽度更宽。 / p>

简而言之:分组UITableViewCell内的标签宽度为280!