如何通过加载html字符串数据知道textView内容高度?
How to know the textView content height by loading html string data?
我有 html 字符串数据,我在文本视图中显示它。
但我想知道关于我的 html 数据的 textView 内容高度。
因为我想添加 textview 作为 UIScrollView 的子视图来显示数据。
我也希望 textview 不滚动,并向用户显示所有数据。
所以,我需要知道textview的高度。
对我有什么想法吗?
谢谢。
do {
let attrStr = try NSAttributedString(
data: htmlString.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
self.textView.attributedText = attrStr //how to know the height about the content?
} catch let error {
print(error)
}
尝试使用此函数获取标签的高度,然后将该高度传递给 textView。希望这能解决您的问题。
func heightForHtmlString(_ text: NSMutableAttributedString, font:UIFont) -> CGFloat {
let label:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 200, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.attributedText = text as NSAttributedString
label.sizeToFit()
return label.frame.height
}
我有 html 字符串数据,我在文本视图中显示它。
但我想知道关于我的 html 数据的 textView 内容高度。
因为我想添加 textview 作为 UIScrollView 的子视图来显示数据。
我也希望 textview 不滚动,并向用户显示所有数据。
所以,我需要知道textview的高度。
对我有什么想法吗?
谢谢。
do {
let attrStr = try NSAttributedString(
data: htmlString.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
self.textView.attributedText = attrStr //how to know the height about the content?
} catch let error {
print(error)
}
尝试使用此函数获取标签的高度,然后将该高度传递给 textView。希望这能解决您的问题。
func heightForHtmlString(_ text: NSMutableAttributedString, font:UIFont) -> CGFloat {
let label:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 200, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.attributedText = text as NSAttributedString
label.sizeToFit()
return label.frame.height
}