簡體   English   中英

在IOS自定義鍵盤的文本字段中獲取當前文本

[英]Get the current text inside of a textfield for IOS custom keyboard

我正在開發IOS定制鍵盤。 我想知道是否有一種方法可以在文本字段中獲取當前文本,以及它如何工作。

例如,我們可以使用textDocumentProxy.hasText()來查看文本字段內部是否包含文本,但是我想知道文本字段內部的確切字符串。

最接近的是textDocumentProxy.documentContextBeforeInputtextDocumentProxy.documentContextAfterInput 這些將尊重句子等,這意味着如果值是一個段落,則只會得到當前句子。 眾所周知,用戶可以通過多次重新定位光標來檢索整個字符串,直到檢索到所有內容為止。

當然,如果該字段期望使用單個值(例如用戶名,電子郵件,ID號等),則通常不必擔心這一點。將輸入上下文前后的值組合在一起就足夠了。

樣例代碼

對於單個短語值,您可以執行以下操作:

let value = (textDocumentProxy.documentContextBeforeInput ?? "") + (textDocumentProxy.documentContextAfterInput ?? "")

對於可能包含句子結尾標點符號的值,由於您需要在單獨的線程上運行它,因此會稍微復雜一些。 因此,您必須移動輸入光標以獲取全文, 因此光標將明顯地移動 還不知道這是否會被AppStore接受(畢竟,Apple可能沒有添加一種簡便的方法來故意獲取全文,以防止官方的自定義鍵盤侵犯用戶的隱私)。

注意:以下代碼基於此Stack Overflow答案,但為Swift進行了修改,刪除了不必要的睡眠,使用了沒有自定義類別的字符串,並使用了更高效的移動過程。

func foo() {
    dispatch_async(dispatch_queue_create("com.example.test", DISPATCH_QUEUE_SERIAL)) { () -> Void in
        let string = self.fullDocumentContext()
    }
}

func fullDocumentContext() {
    let textDocumentProxy = self.textDocumentProxy

    var before = textDocumentProxy.documentContextBeforeInput

    var completePriorString = "";

    // Grab everything before the cursor
    while (before != nil && !before!.isEmpty) {
        completePriorString = before! + completePriorString

        let length = before!.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)

        textDocumentProxy.adjustTextPositionByCharacterOffset(-length)
        NSThread.sleepForTimeInterval(0.01)
        before = textDocumentProxy.documentContextBeforeInput
    }

    // Move the cursor back to the original position
    self.textDocumentProxy.adjustTextPositionByCharacterOffset(completePriorString.characters.count)
    NSThread.sleepForTimeInterval(0.01)

    var after = textDocumentProxy.documentContextAfterInput

    var completeAfterString = "";

    // Grab everything after the cursor
    while (after != nil && !after!.isEmpty) {
        completeAfterString += after!

        let length = after!.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)

        textDocumentProxy.adjustTextPositionByCharacterOffset(length)
        NSThread.sleepForTimeInterval(0.01)
        after = textDocumentProxy.documentContextAfterInput
    }

    // Go back to the original cursor position
    self.textDocumentProxy.adjustTextPositionByCharacterOffset(-(completeAfterString.characters.count))

    let completeString = completePriorString + completeAfterString

    print(completeString)

    return completeString
}

暫無
暫無

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

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