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から単語全体を取得するにはどうすればよいですか?
いいね。それは私が与えたロール・ツー・オウン自身の答えよりはるかに優れた解決策です。 –