我试图使用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:[email protected]\">[email protected]</a></p></html>"
我有一个名为convertHTML()
的函数,它使用html文档类型选项将字符串转换为NSAttributedString,我用它来分配给UITextView的属性文本:
textView.attributedText = htmlString.convertHTML()
TextField是selectable
但不是editable
。加载页面时,您可以看到超链接样式(蓝色文本)和所有内容,但您无法点击链接并打开邮件应用程序。
我假设我需要将“mailto:...”更改为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:[email protected]\">[email protected]</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)