对于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中使用:
label.attributedText = htmlText.htmlToString