Swift:在标签或textView或者UILabel中显示HTML数据

对于Swift 4:

extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}

然后,只要您想将HTML文本放在UITextView或者UILabel中使用:

label.attributedText = htmlText.htmlToString

你可能感兴趣的:(Swift:在标签或textView或者UILabel中显示HTML数据)