ios - 在 UITextview 中获取被点击的单词
<p><p>我添加了一个最初不可编辑的 uitextview。我添加了一个轻击手势,使编辑变为真。在点击手势选择器中,我得到了正在点击的单词。我尝试了很多解决方案,但没有一个适合我作为完整的解决方案。如果不滚动 TextView ,每个解决方案都有效。但是,如果我滚动 TextView ,则不会检索到确切的单词。这是我获取点击词的代码:</p>
<pre><code> @objc func handleTap(_ sender: UITapGestureRecognizer) {
notesTextView.isEditable = true
notesTextView.textColor = UIColor.white
if let textView = sender.view as? UITextView {
var pointOfTap = sender.location(in: textView)
print("x:\(pointOfTap.x) , y:\(pointOfTap.y)")
let contentOffsetY = textView.contentOffset.y
pointOfTap.y += contentOffsetY
print("x:\(pointOfTap.x) , y:\(pointOfTap.y)")
word(atPosition: pointOfTap)
}
func word(atPosition: CGPoint) -> String? {
if let tapPosition = notesTextView.closestPosition(to: atPosition) {
if let textRange = notesTextView.tokenizer.rangeEnclosingPosition(tapPosition , with: .word, inDirection: 1) {
let tappedWord = notesTextView.text(in: textRange)
print("Word: \(tappedWord)" ?? "")
return tappedWord
}
return nil
}
return nil
}
</code></pre>
<h1>已编辑:</h1>
<p>这是有问题的演示项目。
<a href="https://github.com/amrit42087/TextViewDemo" rel="noreferrer noopener nofollow">https://github.com/amrit42087/TextViewDemo</a> </p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>Swift 4 中最好最简单的方法</p>
<p><strong>方法 1:</strong></p>
<p><strong>第 1 步:在 TextView 上添加点按手势</strong></p>
<pre><code>let tap = UITapGestureRecognizer(target: self, action: #selector(tapResponse(recognizer:)))
textViewTC.addGestureRecognizer(tap)
</code></pre>
<p><strong>第 2 步:实现点击手势</strong></p>
<pre><code>@objc func tapResponse(recognizer: UITapGestureRecognizer) {
let location: CGPoint = recognizer.location(in: textViewTC)
let position: CGPoint = CGPoint(x: location.x, y: location.y)
let tapPosition: UITextPosition = textViewTC.closestPosition(to: position)!
guard let textRange: UITextRange = textViewTC.tokenizer.rangeEnclosingPosition(tapPosition, with: UITextGranularity.word, inDirection: 1) else {return}
let tappedWord: String = textViewTC.text(in: textRange) ?? ""
print("tapped word ->", tappedWord)
}
</code></pre>
<p>是的,就是这样。去吧。</p>
<p><strong>方法 2:</strong></p>
<p>另一种方法是您可以为 textview 启用链接,然后将其设置为属性。这是一个例子</p>
<pre><code>var foundRange = attributedString.mutableString.range(of: "Terms of Use") //mention the parts of the attributed text you want to tap and get an custom action
attributedString.addAttribute(NSAttributedStringKey.link, value: termsAndConditionsURL, range: foundRange)
</code></pre>
<p>将此属性文本设置为Textview和<code>textView.delegate = self</code></p>
<p>现在你只需要在</p>中处理响应
<pre><code>func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
</code></pre>
<p>希望对您有所帮助。一切顺利。</p></p>
<p style="font-size: 20px;">关于ios - 在 UITextview 中获取被点击的单词,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/48474488/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/48474488/
</a>
</p>
页:
[1]