我正在使用UITextView显示以下文本:
txtTest.userInteractionEnabled = true;
txtTest.selectable = true
txtTest.dataDetectorTypes = .Link;
txtTest.text = "<p>لتيتنظربهاإلىالأمورتؤثربنجاحكفيالعملفعلًاأتعرفالقولالمأثورالقديملاتنظرللنصفالفارغمنالكأسوالطريقةالتيتنظربهاإلىالأمورتؤثربنجاحكفيالعملفعلًا</p><a href=\"https://google.com\" target=\"_blank\">رابط خارجي external link</a>"
在text رابط خارجي external link
上无法点击UITextView
链接。可点击区域位于UITextView
中的其他位置。我只是通过点击UITextView
上的任意位置找到了它
不知道是UITextView的bug,还是我这边少了点什么。如果有人遇到了同样的问题并找到了解决方案?
发布于 2018-06-22 03:02:32
你必须让你的UIViewController
确认UITextViewDelegate
协议并实现textView(_:shouldInteractWith:in:interaction:).别忘了delegate
和dataDetectorTypes
,你的标准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
}
而不是使用锚定标签,使用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
如果你想使用超文本标记语言,那么你仍然需要把它转换成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()
https://stackoverflow.com/questions/50973984
复制相似问题