При нажатии на UITextVIew я пытаюсь получить слово, в котором произошло крана (с использованием UITapGestureRecognizer, помещенного в UITextView). Я могу захватить индекс выбранного персонажа, но я не получаю успеха, хватая полное слово, это только кажется срабатывающим, когда я нажимаю только первую букву.Получить слово из символьного индекса в 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 с символьным индексом каждый раз?
О, хорошо. Это намного лучшее решение, чем ответ, который я дал. –