Calculate Height Of NSAttributedString Containing HTML

限于喜欢 提交于 2020-02-05 05:31:04

问题


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)
}

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.

I tried the following code.

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)

This returns 462 which is way lesser then actual height, how to correctly calculate the height for this?

Thanks.


回答1:


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)


来源:https://stackoverflow.com/questions/44322345/calculate-height-of-nsattributedstring-containing-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!