超链接可点击区域在UITextView中受到干扰



我正在使用UITextView显示以下文本:

txtTest.userInteractionEnabled = true;
txtTest.selectable = true
txtTest.dataDetectorTypes = .Link;
txtTest.text = "<p>لتيتنظربهاإلىالأمورتؤثربنجاحكفيالعملفعلًاأتعرفالقولالمأثورالقديملاتنظرللنصفالفارغمنالكأسوالطريقةالتيتنظربهاإلىالأمورتؤثربنجاحكفيالعملفعلًا</p><a href="https://google.com" target="_blank">رابط خارجي external link</a>"

UITextView链接在文本رابط خارجي external link上不可点击。可点击区域在UITextView中的其他地方。我只是通过点击UITextView上的随机位置来弄清楚的

不知道是UITextView的错误还是我这边缺少的东西。如果有人遇到同样的问题并找到任何解决方案?

你必须让你的UIViewController确认UITextViewDelegate协议并实现textView(_:shouldInteractWith:in:interaction:(。 您的标准UITextView设置应如下所示,不要忘记delegatedataDetectorTypes

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
}

而不是使用锚标签,请使用attributedText以快速的方式检测所选文本中的链接。

let targetLink = "https://google.com"
let yourAttributes = [NSForegroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.systemFont(ofSize: 15)]
let yourOtherAttributes = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont.systemFont(ofSize: 25)]
let partOne = NSMutableAttributedString(string: "لتيتنظربهاإلىالأمورتؤثربنجاحكفيالعملفعلًاأتعرفالقولالمأثورالقديملاتنظرللنصفالفارغمنالكأسوالطريقةالتيتنظربهاإلىالأمورتؤثربنجاحكفيالعملفعلً ", attributes: yourAttributes)
let partTwo = NSMutableAttributedString(string: " رابط خارجي external link", attributes: yourOtherAttributes)
let text = " رابط خارجي external link"
let str = NSString(string: text)
let theRange = str.range(of: text)
partTwo.addAttribute(NSLinkAttributeName, value: targetLink, range: theRange)
let combination = NSMutableAttributedString()
combination.append(partOne)
combination.append(partTwo)
txtTest.attributedText = combination

如果要使用HTML,则仍然必须将其转换为NSAttributedString。此函数会将所有 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 stringValue = "<p>لتيتنظربهاإلىالأمورتؤثربنجاحكفيالعملفعلًاأتعرفالقولالمأثورالقديملاتنظرللنصفالفارغمنالكأسوالطريقةالتيتنظربهاإلىالأمورتؤثربنجاحكفيالعملفعلًا</p><a href="https://google.com" target="_blank">رابط خارجي external link</a>"
txtTest.attributedText = stringValue.convertHtml()

最新更新