我有一个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上的输出如下所示,但点击时没有任何反应:
这是Google Home。
如何在野生动物园中打开它?
从你的行:
simpleTextLabel.attributedText = text.htmlToAttributedString
我们可以假设simpleTextLabel
是一个UILabel
。
这是从UILabel
到“不可互动”的基本行为。您可以在其上添加点按手势,但它会将其转换为UIButton
。
有一些技巧可以使用UILabel
,查找确切地点击它的位置,检查是否有链接等。寻找“UILabel Clickable”:Create tap-able "links" in the NSAttributedString of a UILabel?等。甚至还有一些第三方库。
我(以我的拙见)认为它是“黑客”。
有一个很好的WWDC 2018 Session: TextKit Best Practices。在2:34,它解释了如果你需要与显示的文本进行交互,更喜欢UITextView
而不是UILabel
。
有一个UITextViewDelegate
方法只是为了:textView(_:shouldInteractWith:in:interaction:)
请注意,UITextView
和UILabel
的渲染存在细微差别。如果你叠加它们,它们将没有相同的“起点”,布局有点不同。但是,如果变化很小,它可以是相同的(例如:How can I make a UITextView layout text the same as a UILabel?)。
还要注意,根据UITextView
对UILabel
视觉渲染的小修改,用户将不会注意到差异(事实上,重要的是,除了使用UITextView
/ UITextViewDelegate
的原生方法之后,另一个使用之后很容易理解开发人员,或者在几个月内,如果你需要做一些小修改)。