ios - 在 Swift 中将 HTML 转换为纯文本

标签 ios swift uitableview

我正在开发一个简单的 RSS 阅读器应用程序作为 Xcode 中的初学者项目。我目前已将其设置为解析提要,放置标题、发布日期、描述和内容,并将其显示在 WebView 中。

我最近决定在用于选择帖子的 TableView 中显示描述(或内容的截断版本)。但是,这样做时:

cell.textLabel?.text = item.title?.uppercaseString
cell.detailTextLabel?.text = item.itemDescription //.itemDescription is a String

它显示帖子的原始 HTML。

我想知道如何将 TableView 的详细 UILabel 的 HTML 转换为纯文本。

谢谢!

最佳答案

您可以添加此扩展以将您的 html 代码转换为常规字符串:

编辑/更新:

Discussion The HTML importer should not be called from a background thread (that is, the options dictionary includes documentType with a value of html). It will try to synchronize with the main thread, fail, and time out. Calling it from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs). The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import.

Xcode 11.4 • Swift 5.2

extension Data {
    var html2AttributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            print("error:", error)
            return  nil
        }
    }
    var html2String: String { html2AttributedString?.string ?? "" }
}

extension StringProtocol {
    var html2AttributedString: NSAttributedString? {
        Data(utf8).html2AttributedString
    }
    var html2String: String {
        html2AttributedString?.string ?? ""
    }
}

cell.detailTextLabel?.text = item.itemDescription.html2String

关于ios - 在 Swift 中将 HTML 转换为纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28124119/

相关文章:

ios - parse.com 'retweet' 模式太冗长

ios - 调整 AVPlayer 大小时的自动布局问题

ios - UICollectionViewCell 嵌入导航 Controller 时下推

ios - 如何手动设置扬声器 Swift 的输出

ios - UITableViewCell,在滑动时显示删除按钮

ios - UITableView setEditing 不会为标签约束更改设置动画

iphone - 如何以编程方式为处于触摸状态的 UIButton 创建灰色覆盖?

ios - 如何使 UIScrollView 高度等于内容高度?

ios - 编辑 tableview Swift 的行高

ios - 在 iOS 6 中调整大小后 MKMapView 变为空白