从 HTML 计算 NSAttributedString 的大小



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

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

// 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];

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

计算包含 HTML 的 NSAttributedString 的高度

好的,

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

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

相关内容

  • 没有找到相关文章

最新更新