[英]How to detect tap on particular line on UITextView?
I have a UITextview
i want to make few words as link so that i can detect tap on them and get a callback function. 我有一个
UITextview
我想做几个词作为链接,以便我可以检测到它们的点击并获取回调函数。 I have made link property of UITextView
as checked and Implemented below delegate methods. 我已经将
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
}
I have also made the string bold and italic by using NSMutableString
我还使用
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
How can I do this? 我怎样才能做到这一点?
To detect a tap on a particular line (as your question's title suggests), then the following code would do the job: 要检测特定行上的轻击(如您的问题的标题所示),那么以下代码即可完成工作:
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)")
}
}
}
The code below is used to call the method above when a tap is detected on our textView. 当在我们的textView上检测到轻敲时,下面的代码用于调用上述方法。
let tap = UITapGestureRecognizer(target: self, action: #selector(didTapTextView(recognizer:)))
tap.cancelsTouchesInView = false
textView.addGestureRecognizer(tap)
However, if you only want to detect taps on links, then you should conform to the UITextViewDelegate
protocol, and implement the following method: 但是,如果只想检测链接上的点击,则应遵循
UITextViewDelegate
协议,并实现以下方法:
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
return true
}
Of course, you need to add the delegate to your textView (eg in viewDidLoad()
) 当然,您需要将委托添加到您的textView中(例如,在
viewDidLoad()
)
textView.delegate = self
PS your UITextView
should not be editable. PS您的
UITextView
应该不可编辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.