计算包含HTML的NSAttributedString的高度 [英] Calculate Height Of NSAttributedString Containing HTML
本文介绍了计算包含HTML的NSAttributedString的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用NSAttributedString通过以下代码显示HTML文本.
I am using NSAttributedString to display HTML text using the following code.
do {
let html = "<span style=\"font-family: Montserrat-ExtraLight; font-size: 14; line-height: 1.5;\">\(clinic.profile!)</span>"
let clinicProfile = try NSAttributedString(
data: (html.data(using: String.Encoding.unicode, allowLossyConversion: true)!),
options: [
NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType
],
documentAttributes: nil
)
contentView.attributedText = clinicProfile
scrollView.addSubview(contentView)
} catch {
print(error)
}
我现在要计算字符串的高度,在HTML中,我正在使用HTML标签,例如p, strong, em, ul > li, ol > li.
I now want to calculate the height of the string, In the HTML, I am using the HTML tags such as p, strong, em, ul > li, ol > li.
我尝试了以下代码.
let size = CGSize(width: view.frame.width, height: 2000)
let boundingBox = contentView.attributedText.boundingRect(
with: size,
options: [.usesLineFragmentOrigin, .usesFontLeading, .usesDeviceMetrics],
context: nil
)
print(boundingBox.height)
这将返回462,比实际高度要小得多,如何正确计算高度?
This returns 462 which is way lesser then actual height, how to correctly calculate the height for this?
谢谢.
推荐答案
我的解决方案确实起作用,问题是我错误地设置了滚动视图的大小,修复了滚动视图的高度,这解决了我的问题.
My solution did work, The problem was that I was incorrectly setting the size of scrollview, fixing the height of scroll view fixed my problem.
let size = CGSize(width: view.frame.width, height: 2000)
let boundingBox = contentView.attributedText.boundingRect(
with: size,
options: [.usesLineFragmentOrigin, .usesFontLeading, .usesDeviceMetrics],
context: nil
)
print(boundingBox.height)
这篇关于计算包含HTML的NSAttributedString的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文