【问题标题】:Calculate size of NSAttributedString from HTML从 HTML 计算 NSAttributedString 的大小
【发布时间】:2019-04-10 00:27:26
【问题描述】:

我正在使用 UITextView 显示来自某些给定 HTML 的 NSAttributedString,其中可以包括粗体、斜体、列表、标记、上标和下标等元素。

目前,下面的代码仅适用于文本段落,但一旦我开始添加更复杂的元素(例如列表和换行符),大小就会完全关闭。

// Create the NSMutableAttributedString from given HTML
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                          NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithData:data options:options
                               documentAttributes:nil error:nil];

// Max size for the text container (no limit on height)
CGSize bounds = CGSizeMake(320.0, CGFLOAT_MAX);

// Set the font and size for better rendering results
UIFont *font = [UIFont fontWithName:@"Roboto" size:14.0];
NSDictionary *attrFont = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
NSRange range = NSMakeRange(0, str.length);
[str addAttributes:attrFont range:range];

// Calcualte the size of the UITextView based on the above parameters
CGRect rect = [str boundingRectWithSize:bounds options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|        NSStringDrawingUsesDeviceMetrics context:nil];

我已经进行了一些搜索并找到了这个帖子,但是在尝试了那里的建议之后它似乎仍然无法正常工作,想知道是否有人知道更好的方法来做到这一点?

Calculate Height Of NSAttributedString Containing HTML

【问题讨论】:

    标签: objective-c uitextview


    【解决方案1】:

    好吧,经过多次摆弄,我发现尺寸实际上是正确的,但是UITextView 有一些填充/插入会导致溢出。在 textView 上设置以下内容解决了问题

    [self.textView setTextContainerInset:UIEdgeInsetsZero];
    self.textView.textContainer.lineFragmentPadding = 0;
    

    【讨论】:

    • “尺寸完全关闭” 和由于小文本视图插图而略微偏离之间存在很大差异。顺便说一句 - 另一种解决方案是通过文本视图的插图调整计算出的文本大小。
    • @rmaddy 乍一看它完全关闭(删除整行),但你可以更新措辞。
    • @rmaddy 你将如何用插图计算?
    • 将文本视图的插入添加到计算出的rect
    猜你喜欢
    • 2017-11-03
    • 2013-01-10
    • 2013-06-25
    • 2014-01-26
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多