NSAttributedString from HTML with Hyperlinks



我正在尝试使用NSAttributedString将包含超链接的大型HTML字符串呈现到UITextView中。除了超链接之外,一切都工作正常,它们实际上并没有打开链接。

举个例子,这是我的html字符串的虚拟版本:

let htmlString = "<html><p>If you would like to contact someone, you can email 
them at <a class=rvts10 href="mailto:some@one.com">some@one.com</a></p></html>"

我有一个名为convertHTML()的函数,它将字符串转换为带有 html 文档类型选项的 NSAttributedString,我用它来分配给 UITextView 的属性文本:

textView.attributedText = htmlString.convertHTML()

文本字段selectable但不是editable。加载页面后,您可以看到超链接样式(蓝色文本(和所有内容,但无法点击链接并打开邮件应用程序。

我认为我需要更改"邮件到:..."到iOS可以识别的其他内容,但我不知道需要做什么才能使此链接可链接。


这是我的 html 方法:

func convertHtml() -> 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()
}
}

我认为您的convertHTML((方法有错误,请检查此

let htmlString = "<html><p>If you would like to contact someone, you can email them at <a class=rvts10 href="mailto:some@one.com">some@one.com</a></p></html>"
// you have to convert string to data
let data = Data(htmlString.utf8)
// then convert data to NSAttributedString with NSAttributedString.DocumentType.htm
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
self.textView.attributedText = attributedString
}

我使用这个扩展:

import Foundation
extension NSAttributedString {
convenience init(htmlString html: String) throws {
try self.init(data: Data(html.utf8), options: [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
], documentAttributes: nil)
}
}

实现后,您可以像这样使用它:

contentTextField.attributedText = try? NSAttributedString(htmlString: aHTMLString)

最新更新