从textView(iOS)中的字符索引获取单词

时间:2017-01-25 19:38:04

标签: ios uitextview

点击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中获取整个单词?

2 个答案:

答案 0 :(得分:0)

问题显然似乎源于我在获取位置后设置的.x和.y值。我所要做的就是删除这些行:

location.x -= textView.textContainerInset.left
location.y -= textView.textContainerInset.top

答案 1 :(得分:0)

如果不出意外,您可以将对rangeEnclosingPosition()的通话更改为粒度.character,然后获取单词字符数组并向后搜索单词边界,然后转发和构建你自己的范围。