美文网首页
Swift关于富文本

Swift关于富文本

作者: 岁变 | 来源:发表于2020-06-08 16:09 被阅读0次

记录几个关于富文本处理的方法

  • 处理网络请求回来的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字符串转换成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
    }

相关文章

网友评论

      本文标题:Swift关于富文本

      本文链接:https://www.haomeiwen.com/subject/zjxrtktx.html