Swift:在标签或textView中显示HTML数据 [英] Swift: Display HTML data in a label or textView

查看:1477
本文介绍了Swift:在标签或textView中显示HTML数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些HTML数据,其中包含标题,段落,图片和列表标签。

I have some HTML data, which contains headings, paragraphs , images and lists tags.

有没有办法在一个 UITextView 或 UILabel

推荐答案

对于Swift 4:

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

然后,只要你想放置HTML文本在UITextView中使用:

Then, whenever you want to put HTML text in a UITextView use:

label.attributedText = htmlText.htmlToString

这篇关于Swift:在标签或textView中显示HTML数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆