UILabel加载Html文件

classTRReadHtmlInfoManager:NSObject{

    funcsetAttributedString(_str:String) ->NSMutableAttributedString{

        // 如果有换行,把\n替换成

        varresultStr = str

        resultStr = resultStr.replacingOccurrences(of:"\n", with:"
")

        // 设置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

    }

}

你可能感兴趣的:(UILabel加载Html文件)