我正在使用html创建NSAttributedString:
let htmlString = "<body style='padding-left:50px'><h1>Hello World</h1><div><a href=https://apple.com/offer/samsung-faq/>Click Here</a></div><p>This is a sample text</p><pre>This is also sample pre text</pre></body>"
在这里,我使用扩展方法将其设置为UILabel
someLabel.attributedText = htmlString.htmlToAttributedString
NSAttributedString扩展:
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
}
这里我想要一个回调方法来检测链接,它在html字符串中作为锚标签存在。如何在单击时获取事件,以及如何在该事件回调中获取url?
请帮帮我。
发布于 2018-06-22 04:50:20
使用UITextView
而不是UILabel
,它有一个将文本转换为超链接的属性。
您必须使您的UIViewController
确认UITextViewDelegate
协议并实现textView(_:shouldInteractWith:in:interaction:
。别忘了delegate
和dataDetectorTypes
,你的标准UITextView
设置应该是这样的。
@IBOutlet weak var txtView: UITextView!
// make IBOutlet of UITextView
txtTest.delegate = self
txtTest.isUserInteractionEnabled = true // default: true
txtTest.isEditable = false // default: true
txtTest.isSelectable = true // default: true
txtTest.dataDetectorTypes = [.link]
UITextViewDelegate
方法shouldInteractWithURL
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
print("Link Selected!")
return true
}
HTML
到NSAttributedString
的扩展:
extension String{
func convertHtml() -> NSAttributedString{
guard let data = data(using: .utf8) else { return NSAttributedString() }
do{
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
}catch{
return NSAttributedString()
}
}
}
然后你可以像这样使用它。
let htmlString = "<body style='padding-left:50px'><h1>Hello World</h1><div><a href=https://apple.com/offer/samsung-faq/>Click Here</a></div><p>This is a sample text</p><pre>This is also sample pre text</pre></body>"
txtTest.attributedText = htmlString.convertHtml()
https://stackoverflow.com/questions/50969015
复制相似问题