簡體   English   中英

在 UITextView 中獲取當前輸入的單詞

[英]Get currently typed word in UITextView

我正在嘗試制作一個“標記窗口”,就像在 Facebook 中使用的那個窗口一樣,您可以在其中鍵入“@”,然后它會在您的朋友之間就標記哪個窗口提出建議。 我希望在我的應用程序中使用此功能,但我終生無法弄清楚如何獲取當前輸入的單詞以過濾建議。

我使用UITextView ,我一直在看這篇文章https://stackoverflow.com/a/27380612/4148782

但是我在將其轉換為 Swift 3 時遇到了問題,即便如此,評論表明這無論如何都沒有解決。

所以我追求的功能是:

  • 用戶開始在UITextView輸入,如果單詞以“@”開頭,我想提取該單詞。
  • 我也想用某個輸入替換這個詞。 假設用戶鍵入@abc並且我過濾了一個說明“ abcdef ”的建議,然后我希望能夠用“ abcdef ”替換 UITextView 中的@abc

請注意,我想要當前輸入的單詞而不是最近輸入的單詞。

這對我有用。

extension UITextView {

var currentWord : String? {

    let beginning = beginningOfDocument

    if let start = position(from: beginning, offset: selectedRange.location),
        let end = position(from: start, offset: selectedRange.length) {

        let textRange = tokenizer.rangeEnclosingPosition(end, with: .word, inDirection: 1)

        if let textRange = textRange {
            return text(in: textRange)
        }
    }
    return nil
   }
}

像往常一樣,我花了相當多的時間試圖讓它起作用,在我發布問題幾分鍾后,我就讓它起作用了。 所以這是我使用的代碼,但我不贊成調用let myRange

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

    let myRange = Range<String.Index>(start: textView.text.startIndex, end: textView.text.startIndex.advancedBy(range.location))
    var subString = textView.text.substringWithRange(myRange)
    subString += text

    let wordArray = subString.componentsSeparatedByString(" ")
    if let wordTyped = wordArray.last {
        currentWord = wordTyped
        print("word typed: " + wordTyped)
    }

    return true
}

斯威夫特 4:

這個解決方案在方法func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool of UITextViewDelegate 中對我func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool

  func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        guard let textFieldText = textView.text,
              let rangeOfTextToReplace = Range(range, in: textFieldText) else {
                return false
        }

        let currentText = textFieldText.replacingCharacters(in: rangeOfTextToReplace, with: text)
    
        return count <= 150
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM