Ios 如何在UITextView上检测特定行上的点击?
我有一个Ios 如何在UITextView上检测特定行上的点击?,ios,swift,uitextview,Ios,Swift,Uitextview,我有一个UITextview我想制作一些单词作为链接,这样我就可以检测到点击它们并获得一个回调函数。我已将UITextView的链接属性设置为在下面的委托方法中检查和实现的属性 func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { print("hello") return true } @available(iOS
UITextview
我想制作一些单词作为链接,这样我就可以检测到点击它们并获得一个回调函数。我已将UITextView
的链接属性设置为在下面的委托方法中检查和实现的属性
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
print("hello")
return true
}
@available(iOS 10.0, *)
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
print("bye")
return true
}
我还使用NSMutableString
let str = NSMutableAttributedString(string: self.tvBottom.text as String, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17.0)])
str.addAttribute(NSLinkAttributeName, value: "http://www.google.com", range: NSRange(location: 4, length: 14))
str.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue , range: NSRange(location: 4, length: 14))
let boldFontAttribute = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 17.0)]
str.addAttributes(boldFontAttribute, range: NSRange(location: 4, length: 14))
str.addAttribute(NSUnderlineStyleAttributeName , value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 4, length: 14))
self.tvBottom.attributedText = str
如何执行此操作?要检测特定行上的点击(如问题标题所示),则以下代码将执行此操作:
func didTapTextView(recognizer: UITapGestureRecognizer) {
if recognizer.state == .recognized {
let location = recognizer.location(ofTouch: 0, in: textView)
if location.y >= 0 && location.y <= textView.contentSize.height {
guard let font = textView.font else {
return
}
let line = Int((location.y - textView.textContainerInset.top) / font.lineHeight) + 1
print("Line is \(line)")
}
}
}
但是,如果只想检测链接上的点击,则应遵循UITextViewDelegate
协议,并实现以下方法:
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
return true
}
当然,您需要将委托添加到您的文本视图中(例如,在viewDidLoad()
中)
另外,您的
UITextView
不应编辑。如果第一行是,您需要在UITextView上启用链接属性,但我想检测用户在UITextView上点击了哪个词,我不确定我是否理解。假设我有一段“这只是一个非常非常好的产品。请单击此处查看更多信息”.现在只需单击此处,我想检测水龙头
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
return true
}
textView.delegate = self