从textView(iOS)中的字符索引获取单词
点击UITextVIew时,我试图获取点击发生的单词(使用放置在UITextVIew中的UITapGestureRecognizer)。我能够抓取所选字符的索引,但抓取完整单词并没有成功,它似乎只在我点击第一个字母时才起作用从textView(iOS)中的字符索引获取单词,ios,uitextview,Ios,Uitextview,点击UITextVIew时,我试图获取点击发生的单词(使用放置在UITextVIew中的UITapGestureRecognizer)。我能够抓取所选字符的索引,但抓取完整单词并没有成功,它似乎只在我点击第一个字母时才起作用 func textTapped(_ tapGestureRecognizer: UITapGestureRecognizer){ if let textView = textTapGestureRecognizer?.view as? UITextView {
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.
}
}
}
}
}
func textTapped(uuTapGestureRecognitizer:UITapGestureRecognitizer){
如果让textView=textTapGestureRecognizer?.view为?UITextView{
让layoutManager=textView.layoutManager
变量位置:CGPoint=texttapgesturecognizer!。位置(在:textView中)
location.x-=textView.textContainerSet.left
location.y-=textView.textContainerSet.top
让characterIndex=layoutManager.characterIndex(对于:位置,在:textView.textContainer中,插入点之间距离的分数:nil)
如果characterIndex
我总是能够打印出字符索引和被点击的字符,然而,抓住这个单词是个问题。如何每次使用字符索引从文本视图中抓取整个单词?问题显然源于获取位置后设置的.x和.y值。我所要做的就是删除这些行:
location.x -= textView.textContainerInset.left
location.y -= textView.textContainerInset.top
如果没有其他内容,您可以将对
RangeEnclosuringPosition()
的调用更改为粒度.character
,然后获取单词的字符数组并向后搜索单词边界,然后向前搜索并自己构建范围。。这是一个比我给出的你自己的答案好得多的解决方案。