在点击 UITextVIew 时,我试图获取点击发生的单词(使用放置在 UITextView 中的 UITapGestureRecognizer)。我能够抓取所选字符的索引,但我没有成功抓取完整的单词,它似乎只在我点击第一个字母时才有效。
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 中获取整个单词?
问题显然源于我在获取位置后设置的 .x 和 .y 值。我所要做的就是删除这些行:
location.x -= textView.textContainerInset.left
location.y -= textView.textContainerInset.top
关于ios - 从 textView 中的字符索引获取单词(iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41860197/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |