ios-Swift:以标签或textVi显示HTML数据
我有一些HTML数据,其中包含标题,段落,图像和列表标签。
有没有一种方法可以在一个UITextView或UILabel中显示此数据?
12个解决方案
146 votes
对于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时,请使用:
textView.attributedText = htmlText.htmlToAttributedString
Roger Carvalho answered 2019-11-15T18:40:49Z
34 votes
这是Swift 3版本:
private func getHtmlLabel(text: String) -> UILabel {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.attributedString = stringFromHtml(string: text)
return label
}
private func stringFromHtml(string: String) -> NSAttributedString? {
do {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let d = data {
let str = try NSAttributedString(data: d,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
return str
}
} catch {
}
return nil