UILabel加載Html文件

classTRReadHtmlInfoManager:NSObject{

? ? funcsetAttributedString(_str:String) ->NSMutableAttributedString{

? ? ? ? // 如果有換行,把\n替換成

? ? ? ? varresultStr = str

? ? ? ? resultStr = resultStr.replacingOccurrences(of:"\n", with:"<br/>")

? ? ? ? // 設置HTML圖片的寬度

? ? ? ? resultStr =String(format: "img{width:%f !important;height:auto}%@", UIConstants.IPHONE_WIDTH - 20, resultStr)


? ? ? ? lethtmlString =try!NSMutableAttributedString(data: resultStr.data(using: .utf8)!, options: [.documentType:NSAttributedString.DocumentType.html, .characterEncoding:NSNumber(value:String.Encoding.utf8.rawValue)], documentAttributes:nil)

? ? ? ? // 設置富文本字的大小

? ? ? ? htmlString.addAttributes([.font:UIFont.systemFont(ofSize:16.0, weight: .regular)], range:NSRange(location:0, length: htmlString.length))

? ? ? ? // 設置行間距

? ? ? ? letparagraphStyle =NSMutableParagraphStyle()

? ? ? ? paragraphStyle.lineSpacing=5.0

? ? ? ? htmlString.addAttributes([.paragraphStyle: paragraphStyle], range:NSRange(location:0, length: htmlString.length))

? ? ? ? returnhtmlString

? ? }


? ? funcgetHTMLHeightByStr(_str:String) ->CGFloat{

? ? ? ? letresultStr =self.setAttributedString(str)

? ? ? ? letcontentSize = resultStr.boundingRect(with:CGSize(width:UIConstants.IPHONE_WIDTH-20.0, height:CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], context:nil).size

? ? ? ? returncontentSize.height

? ? }

}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容