Swift關(guān)于富文本

記錄幾個(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: "&lt;", with: "<")
        
        content = content.replacingOccurrences(of: "&gt;", with: ">")
        
        content = content.replacingOccurrences(of: "&quot;", 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
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容