我有一个带有 UITableViewCell
的 UITableView
,我在函数 heightForRowAtIndexPath
中以以下方式设置每个单元格的高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
NSStringDrawingOptions opts = (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading);
CGSize boundingRect = CGSizeMake(450.f, CGFLOAT_MAX);
CGSize size = [cell.detailTextLabel.text boundingRectWithSize:boundingRect
options:opts
attributes:[cell.detailTextLabel.attributedText attributesAtIndex:0 effectiveRange:nil]
context:nil].size;
CGFloat height = size.height;
size = [cell.textLabel.text boundingRectWithSize:boundingRect
options:opts
attributes:[cell.textLabel.attributedText attributesAtIndex:0 effectiveRange:nil]
context:nil].size;
height += size.height;
return height;
}
但是我得到的单元格对于文本来说太小了,而且较长的文本也不适合:
在单元格中写入的文本按以下方式设置:
NSString *nickName = @"some nickname"; // gets the nickname
NSString title = [NSString stringWithFormat:@"%@ wrote:", nickName];
NSString *detail = @"some text"; // gets the content of the message
[cell.textLabel setText: title];
[cell.detailTextLabel setText: detail];
cell.detailTextLabel.numberOfLines = 0;
cell.detailTextLabel.lineBreakMode = NSLineBreakByWordWrapping;
为什么单元格的高度太短了?
最佳答案
来自方法boundingRectWithSize:options:attributes:context:
https://developer.apple.com/reference/foundation/nsstring/1524729-boundingrectwithsize :
“此方法返回字符串中字形的实际边界”
缺少的是单元格的边距,可以通过 cell.layoutMargins
访问:
height += cell.layoutMargins.top + cell.layoutMargins.bottom;
关于ios - 为什么 UITableViewCell 的高度小于其文本的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41532196/