• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 似乎无法为 UILabel 计算正确的 NSAttributedString 行高

[复制链接]
菜鸟教程小白 发表于 2022-12-13 07:27:21 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在使用 NSAttributedString's boundingRectWithSizeptions:context: 方法来计算某些文本的预期高度,在阅读 this article from objc.io 之后

+(CGSize)postLabelSizeForPostANKPost *)post
{
  CGFloat labelWidth = 220.0f;
  NSAttributedString *text = [BXTPostCell mutableAttributedStringForPost:post];
  NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
  CGRect boundingRect = [text boundingRectWithSize:CGSizeMake(labelWidth, CGFLOAT_MAX)
                                         optionsptions
                                         context:nil];
  CGFloat height = (CGFloat) (ceil(boundingRect.size.height));

  return CGSizeMake(labelWidth, height);
}

但是,当我使用这种方法时,文本实际上并不适合这个大小 - 大小总是太短。

起初,我认为问题出在表情符号字符上 - 但应用程序中的许多 tableviewcells 似乎都发生了这种情况。

更新: 我和几个人谈过,听起来这个问题可能是 boundingRectWithSizeptions:context: 的潜在错误。我想出了一个解决方法:创建一个虚拟 UILabel,赋予它与 tableview 单元格中的 UILabel 相同的属性(numberOfLines 等)和然后使用 sizeThatFits: 来计算尺寸。可以肯定的是,这是一个 hack - 但它充分解决了我的问题。不过,我希望它更优雅!



Best Answer-推荐答案


我在尝试计算 UITextView 的属性文本大小时遇到​​了同样的效果。我遇到了this answer to another question .

诀窍是使用 NSLayoutManager's usedRectForTextContainer: .巧妙的是,此方法不需要与 UITextView 结合使用。这意味着您可以在 mainThread 之外使用它,这是预先计算 UITableViewCell 高度的关键。

我是这样使用它的:

- (CGSize)rectForAttributedStringNSAttributedString *)string withSizeCGSize)theSize
{
    if (!string || CGSizeEqualToSize(theSize, CGSizeZero)) {
        return CGSizeZero;
    }

    // setup TextKit stack
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:theSize];
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:string];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    [layoutManager addTextContainer:textContainer];
    [textStorage addLayoutManager:layoutManager];

    // query for size
    CGRect rect = [layoutManager usedRectForTextContainer:textContainer];

    return CGSizeMake(ceilf(rect.size.width), ceilf(rect.size.height));
}

为了方便起见,我创建了一个方便的方法来计算特定宽度的高度:

- (CGFloat)textViewHeightForAttributedStringNSAttributedString *)string withWidthCGFloat)width
{
    return [self rectForAttributedString:string withSize:CGSizeMake(width, CGFLOAT_MAX)].height;
}

希望这会有所帮助。


PS。我对整个编程有点陌生,所以如果我的代码可以优化,请告诉我。

关于ios - 似乎无法为 UILabel 计算正确的 NSAttributedString 行高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22916566/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap