【发布时间】:2017-01-25 19:38:03
【问题描述】:
在点击 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 中获取整个单词?
【问题讨论】:
标签: ios uitextview