获取 IOS 自定义键盘的文本字段内的当前文本

2023-12-31

我正在开发一个IOS自定义键盘。我想知道是否有一种方法可以获取文本字段内的当前文本以及它如何工作。

例如,我们可以使用textDocumentProxy.hasText()查看文本字段内是否有文本,但我想知道文本字段内的确切字符串。


最接近的事情是textDocumentProxy.documentContextBeforeInput and textDocumentProxy.documentContextAfterInput。这些将尊重句子等,这意味着如果该值是一个段落,您将只获得当前的句子。众所周知,用户可以通过多次重新定位光标来检索整个字符串,直到检索到所有内容。

当然,如果该字段需要单个值(例如用户名、电子邮件、ID 号等),您通常不必担心这一点。组合输入上下文之前和之后的值就足够了。

示例代码

对于单个短语值,您可以这样做:

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

对于可能包含句子结尾标点符号的值,它会稍微复杂一些,因为您需要在单独的线程上运行它。因此,您必须移动输入光标才能获取全文,光标将明显移动。目前还不清楚这是否会被 AppStore 接受(毕竟,苹果为了防止官方定制键盘侵犯用户隐私,可能没有故意添加获取全文的简单方法)。

注意:以下代码基于这个堆栈溢出答案 https://stackoverflow.com/a/29121560/1144689除了针对 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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取 IOS 自定义键盘的文本字段内的当前文本 的相关文章

随机推荐