我有一个文本字段,我不想在其中允许前导空格。所以我实施了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 建议?
解决方法是修剪多字符插入中的空格,但首先我想看看我是否缺少一种以干净的方式处理问题的方法。