2017-01-25 4 views
0

UITextVIewのタップで、(UITextViewに配置されたUITapGestureRecognizerを使用して)タップが発生した単語を取得しようとしています。私は選択された文字のインデックスをつかむことができますが、私は完全な単語をつかむことに成功していない、それは最初の文字だけをタップすると動作するようです。textView(iOS)の文字インデックスから単語を取得

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 < textView.textStorage.length { 

      // print the character index successfully 
      print("character index: \(characterIndex)") 

      // 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("character at index: \(substring)") 

      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("selected word :\(tappedWord)") 
        //This only prints when I seem to tap the first letter of word. 
       } 
      } 
     } 
    } 
} 

私はいつも文字インデックスとタップされた文字を印刷できますが、単語をつかむことは問題です。毎回文字インデックスを持つtextViewから単語全体を取得するにはどうすればよいですか?

答えて

0

問題は明らかに場所を取得した後に設定した.xと.yの値に起因するようです。何もない場合は、あなたがして転送し、単語境界のために後方の単語の文字と検索の配列を取得、その後、粒度.characterrangeEnclosingPosition()にお電話を変更することができ

location.x -= textView.textContainerInset.left 
location.y -= textView.textContainerInset.top 
+1

いいね。それは私が与えたロール・ツー・オウン自身の答えよりはるかに優れた解決策です。 –

0

:私がしなければならなかったすべては、これらの行を削除しました自分で範囲を構築してください。

関連する問題