ios - 为什么 UITableViewCell 的高度小于其文本的高度?

标签 ios objective-c uitableview

我有一个带有 UITableViewCellUITableView,我在函数 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;
}

但是我得到的单元格对于文本来说太小了,而且较长的文本也不适合:

if the text doesn't fit you must acquit

在单元格中写入的文本按以下方式设置:

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/

相关文章:

ios - 如何获取 UITableView 内的 UICollectionView 内的数组数组并返回正确数量的项目?

iphone - 根据 UILabel 大小展开 UITableViewCell

ios - 如何使用Sprite Kit创建弯曲的水平边界

iOS - 无法检测到应用程序崩溃

iphone - 如何禁用触摸检测?

iphone - 无法更新 uitableview 行

ios - 集成触摸姿势

ios - 如何使用 switch 语句更改 UIButton 的图像?

objective-c - 如何关闭前面的应用程序窗口

ios - 我们可以为返回可选值的 swift 函数添加 @objc 吗?