2016-08-16 29 views
1

我試圖使一個「標記窗口」很像Facebook中使用的那個鍵入「@」的那個,它在你的朋友之間建立標籤的建議。我想在我的應用程序中使用此功能,但是我無法爲我的生活弄清楚如何獲取當前鍵入的單詞以過濾建議。獲取當前鍵入的單詞在UITextView

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

但我有翻譯這斯威夫特3個問題,即使如此的評論認爲,這無論如何都不會得到解決。

所以我之後的功能:

  • 用戶開始輸入在UITextView,如果用字開頭的「@」我想提取字。
  • 我想用某個輸入替換這個單詞。比方說,用戶類型@abc我篩選其中規定的建議「ABCDEF」的話,我希望能夠用「ABCDEF」,更換@abc在UITextView的。

注意,我想這個詞目前得到輸入和最近打的單詞。

+0

你知道,有一個網站,從OBJ-C轉化爲SWIFT稱爲[https://objectivec2swift.com/](https://objectivec2swift.com/) – Tj3n

+0

酷,不知道!沒有那個網站,但得到它的工作,謝謝。將用於未來的參考。 – ClockWise

回答

1

像往常一樣,我花了相當長的時間試圖讓這個工作,並在我發佈了問題,我得到它的工作分鐘後。所以這裏是我使用的代碼,但我已棄用呼籲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 
} 
3

這對我有用。

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 
    } 
} 
相關問題