記錄幾個(gè)關(guān)于富文本處理的方法
- 處理網(wǎng)絡(luò)請(qǐng)求回來(lái)的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字符串轉(zhuǎn)換成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()
}
``
- 計(jì)算富文本的高度用于自適應(yīng)高用
``` ///計(jì)算高度
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
}