[英]Autofit table view cell in iOS 7
我知道这个问题已经被问过很多次了,但是我一直在努力寻找正确的iOS7实现。
我有一个由从我的服务器检索JSON数据的数组填充的tableview。 该数据可以是任何长度。 现在,我只能达到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);
}
您只需要正确实现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中弃用,并已被另一种方法替代,但是我不确定如何使用它:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.