Swift关于富文本

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

  • 处理网络请求回来的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 = " \n \n \n \n \n" + content + ""
        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关于富文本)