我有一个 HTML 格式的文本。我正在使用 NSAttributed 字符串的属性来解析它。它很好地解析文本并显示在标签上。但是,锚标记的解析不会使链接可点击。这是我用于解析的以下代码。
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 ?? ""
}
当我运行应用程序并将值赋给标签时:
text = "<p>This is <a href=\"http://www.google.com\">Google Home</a></p>"
simpleTextLabel.attributedText = text.htmlToAttributedString
iOS App 上的输出如下所示,但单击时没有任何反应:
这是谷歌主页。
我怎样才能让它在 safari 中打开?