首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在从html字符串创建的NSAttributedString中检测锚标签链接点击

如何在从html字符串创建的NSAttributedString中检测锚标签链接点击
EN

Stack Overflow用户
提问于 2018-06-21 20:50:17
回答 1查看 2.2K关注 0票数 3

我正在使用html创建NSAttributedString:

代码语言:javascript
复制
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

代码语言:javascript
复制
someLabel.attributedText = htmlString.htmlToAttributedString

NSAttributedString扩展:

代码语言:javascript
复制
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?

请帮帮我。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-22 04:50:20

使用UITextView而不是UILabel,它有一个将文本转换为超链接的属性。

您必须使您的UIViewController确认UITextViewDelegate协议并实现textView(_:shouldInteractWith:in:interaction:。别忘了delegatedataDetectorTypes,你的标准UITextView设置应该是这样的。

代码语言:javascript
复制
@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

代码语言:javascript
复制
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    print("Link Selected!")
    return true
}

HTMLNSAttributedString的扩展:

代码语言:javascript
复制
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()
        }
    }
}

然后你可以像这样使用它。

代码语言:javascript
复制
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()
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50969015

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档