QuickType 预测会考虑应该被我的 UITextFieldDelegate 阻止的击键

2023-12-24

我有一个文本字段,我不想在其中允许前导空格。所以我实施了textField(textField:shouldChangeCharactersInRange:replacementString:)并阻止将文本更改为以空格开头的内容的尝试。这按预期工作。

不幸的是这会搞乱 QuickType。每次我在空白字段中按空格(然后我的文本字段会忽略该空格)时,Quicktype 文本都会以该空格作为前缀。更清楚地说,QuickType 将插入的文本带有前缀,额外的空格不会显示在 QuickType 栏的 UI 中。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let currentText = textField.text as NSString
    let proposedText = currentText.stringByReplacingCharactersInRange(range, withString: string)
    if !proposedText.isEmpty {
        let firstCharacterString = String(proposedText[proposedText.startIndex]) as NSString
        if firstCharacterString.rangeOfCharacterFromSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).location == 0 {
            println("starts with whitespace \"\(proposedText)\"")
            return false
        }
    }
    return true
}

以下是一些日志记录,用于查看当我按空格键 5 次,然后按I'm快速输入建议:

starts with whitespace " "           // pressing space key
starts with whitespace " "
starts with whitespace " "
starts with whitespace " "
starts with whitespace " "
starts with whitespace "     I'm"    // Inserted by QuickType after pressing the "I'm" suggestion
starts with whitespace " "           // Inserted by QuickType as well

通过检查该委托方法中的变量,我可以验证问题确实出在从 UITextField 获取的替换字符串上。它已经包含以空格为前缀的建议。

有谁知道我如何防止这种情况,或者如何“重置”QuickType 建议?

解决方法是修剪多字符插入中的空格,但首先我想看看我是否缺少一种以干净的方式处理问题的方法。


经过更多测试,我得出的结论是这是一个错误。

首先,我认为键盘和 QuickType 与 UITextField 是解耦的。但事实并非如此。更改填充文本字段中光标的位置实际上会更改快速类型建议。所以textField实际上是与quicktype通信的。

所以我提交了一个错误。

苹果的错误:rdar://19250739
OpenRadar 的错误:5794406481264640 http://openradar.appspot.com/radar?id=5794406481264640

如果有人对解决方法感兴趣:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let currentText = textField.text as NSString
    let proposedText = currentText.stringByReplacingCharactersInRange(range, withString: string)

    if proposedText.hasPrefix(" ") {
        // Don't allow space at beginning
        println("Ignore text \"\(proposedText)\"")

        // workaround
        if textField.text == "" && countElements(string) > 1 {
            // multi insert into empty field. probably from QuickType
            // so we should strip whitespace and set new text directly
            let trimmedString = proposedText.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
            println("Inserted \"\(trimmedString)\" with Quicktype. ")
            textField.text = trimmedString
        }

        return false
    }
    return true
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

QuickType 预测会考虑应该被我的 UITextFieldDelegate 阻止的击键 的相关文章

随机推荐