【发布时间】:2015-02-06 07:39:54
【问题描述】:
我有一个 textField,我不想在其中允许前导空格。所以我实现了textField(textField:shouldChangeCharactersInRange:replacementString:) 并阻止了将文本更改为以空格开头的内容的尝试。这按预期工作。
不幸的是,这弄乱了 QuickType。每次我在一个空字段中按空格,然后我的 textField 会忽略它,Quicktype 文本就会以这个空格为前缀。更清楚地说,QuickType 将插入的文本带有 get 前缀,额外的空格不会显示在 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 QuickType 建议时发生了什么:
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 建议吗?
一种解决方法是从多字符插入中删除空格,但首先我想看看我是否缺少一种以干净的方式处理问题的方法。
【问题讨论】:
标签: cocoa-touch swift uitextfield quicktype