菜鸟教程小白 发表于 2022-12-11 18:43:37

ios - 从 textView 中的字符索引获取单词(iOS)


                                            <p><p>在点击 UITextVIew 时,我试图获取点击发生的单词(使用放置在 UITextView 中的 UITapGestureRecognizer)。我能够抓取所选字符的索引,但我没有成功抓取完整的单词,它似乎只在我点击第一个字母时才有效。 </p>

<pre><code>func textTapped(_ tapGestureRecognizer: UITapGestureRecognizer){
    if let textView = textTapGestureRecognizer?.view as? UITextView {
      let layoutManager = textView.layoutManager
      var location: CGPoint = textTapGestureRecognizer!.location(in: textView)
      location.x -= textView.textContainerInset.left
      location.y -= textView.textContainerInset.top

      let characterIndex = layoutManager.characterIndex(for: location, in: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
      if characterIndex &lt; textView.textStorage.length {

            // print the character index successfully
            print(&#34;character index: \(characterIndex)&#34;)

            // print the character at the index successfully
            let myRange = NSRange(location: characterIndex, length: 1)
            let substring = (textView.attributedText.string as NSString).substring(with: myRange)
            print(&#34;character at index: \(substring)&#34;)

            let tapPosition: UITextPosition? = textView.closestPosition(to: location)
            //fetch the word at this position (or nil, if not available)
            if let textRange = textView.tokenizer.rangeEnclosingPosition(tapPosition!, with: .word, inDirection: 1) {
                if let tappedWord = textView.text(in: textRange) {
                  print(&#34;selected word :\(tappedWord)&#34;)
                  //This only prints when I seem to tap the first letter of word.
                }
            }
      }
    }
}
</code></pre>

<p>我总是能够打印出字符索引和被点击的字符,但是,捕获单词是个问题。如何每次都从带有字符索引的 textView 中获取整个单词?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>问题显然源于我在获取位置后设置的 .x 和 .y 值。我所要做的就是删除这些行:</p>

<pre><code>location.x -= textView.textContainerInset.left
location.y -= textView.textContainerInset.top
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 从 textView 中的字符索引获取单词(iOS),我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/41860197/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/41860197/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 从 textView 中的字符索引获取单词(iOS)