You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift自定义键盘中textDocumentProxy.documentContextBeforeInput换行后读取异常

iOS自定义键盘documentContextBeforeInput获取换行符前内容异常问题

我在自定义键盘应用中,通过textDocumentProxy输入包含换行符\n和标点的文本时,调用textDocumentProxy.documentContextBeforeInput无法获取光标前的完整内容。比如光标放在“Good morning”中间位置时,仅返回“Good”,“Hi folks,”等换行前的内容完全取不到。

测试代码

var inputText = "Hi folks,\n\nGood morning to everyone "
var txtBeforeCursor = textDocumentProxy.documentContextBeforeInput ?? ""
print("Before Cursor text : ",txtBeforeCursor)

输出结果

Before Cursor text : Good

问题原因及解决办法

  • API本身限制:documentContextBeforeInput的设计逻辑是仅返回光标所在当前行的前置文本,不会跨换行符读取之前行的内容,这是系统默认行为。
  • 替代实现方案:通过textDocumentProxy.adjustTextPosition(byCharacterOffset:)逐行回溯,拼接完整的前置内容,示例代码如下:
func getFullContextBeforeCursor() -> String {
    var fullContext = ""
    var currentContext = textDocumentProxy.documentContextBeforeInput ?? ""
    fullContext = currentContext
    
    // 回溯读取之前的行内容
    while true {
        // 计算回退字符数(当前内容长度+换行符长度)
        let offset = -(currentContext.count + 1)
        textDocumentProxy.adjustTextPosition(byCharacterOffset: offset)
        
        let previousContext = textDocumentProxy.documentContextBeforeInput ?? ""
        if previousContext.isEmpty {
            // 无更多内容,恢复光标原位置
            textDocumentProxy.adjustTextPosition(byCharacterOffset: fullContext.count)
            break
        }
        fullContext = previousContext + "\n" + fullContext
        currentContext = previousContext
    }
    return fullContext
}
  • 注意事项:使用adjustTextPosition会临时移动光标,必须在最后恢复原位置;不同输入框对换行符的处理存在差异,需做兼容性测试;避免高频调用此方法,防止影响输入流畅度。

内容的提问来源于stack exchange,提问作者Pavunraj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:00:07