OGeek|极客世界-中国程序员成长平台

标题: ios - 似乎无法为 UILabel 计算正确的 NSAttributedString 行高 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 07:27
标题: ios - 似乎无法为 UILabel 计算正确的 NSAttributedString 行高

我正在使用 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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4