记录几个关于富文本处理的方法
- 处理网络请求回来的html字符串
func getHtmlStrWith(webStr: String) -> String {
var content = webStr.replacingOccurrences(of: "&quot", with: "'")
content = content.replacingOccurrences(of: "<", with: "<")
content = content.replacingOccurrences(of: ">", with: ">")
content = content.replacingOccurrences(of: """, with: "\"")
let htmlStr = "<html> \n<head> \n<meta name=\"viewport\" content=\"initial-scale=1.0, maximum-scale=1.0, user-scalable=no\"/> \n<style type=\"text/css\"> \nbody {font-size:15px;}\n</style> \n</head> \n<body><script type='text/javascript'>window.onload = function(){\nvar $img = document.getElementsByTagName('img');\nfor(var p in $img){\n$img[p].style.width = '100%%';\n$img[p].style.height ='auto'\n}\n}</script>" + content + "</body></html>"
return htmlStr
}
- 处理后的html字符串转换成NSMutableAttributedString
func getAttriFrom(htmlstr: String) -> NSMutableAttributedString {
let attStr = try? NSMutableAttributedString.init(data: htmlstr.data(using: String.Encoding.utf8)!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
return attStr ?? NSMutableAttributedString()
}
``
- 计算富文本的高度用于自适应高用
``` ///计算高度
private func getCountentH(attrStr: NSMutableAttributedString)->CGFloat {
let contentHegiht = attrStr.boundingRect(with: CGSize(width: S_W, height: 100000), options: [.usesLineFragmentOrigin,.usesFontLeading], context: nil).height
return contentHegiht
}