问题描述
我正在使用nsattribatedstring使用以下代码显示HTML文本.
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.
我尝试了以下代码.
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的实际高度要比实际高度要少,如何正确计算此高度?
谢谢.
推荐答案
我的解决方案确实有效,问题是我错误地设置了卷轴的大小,固定滚动视图的高度解决了我的问题.
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)
问题描述
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.
推荐答案
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和NSAttributedString到HTML
NSAttributedString boundingRect返回错误的高度
来自NSAttributedString的HTML
iOS NSAttributedString to HTML
如何在iOS6中计算一个给定宽度的NSAttributedString的高度?
在Autolayout和使用NSAttributedString计算高度中,哪一个是实现UITableViewCell的动态高度的最佳方法?
包含卡片的GridView不能正确计算高度
在NSAttributedString中的HTML渲染非常慢
如何计算html字符串的高度?
在HTML中如何计算文本框的高度