【问题标题】:Get word from character index in textView (iOS)从 textView 中的字符索引获取单词(iOS)
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 哦,太好了。这比我自己给出的答案要好得多。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 2018-09-23
      • 1970-01-01
      • 2020-12-01
      相关资源
      最近更新 更多