textField 应该执行以下操作:
User types "w" -> textField: "w?"
User types "ho are you" -> textfield: "who are you?
现在对于每个输入“?”的字符添加在它之前。
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
let newLength = text.characters.count
if newLength <= 25 {
cLabel.text = String(25 - newLength)
if text.isEmpty { //Checking if the input field is not empty
ahskButton.userInteractionEnabled = false //Disabling the button
ahskButton.enabled = false
} else {
ahskButton.userInteractionEnabled = true //Enabling the button
ahskButton.enabled = true
textField.text! += "?" //NOT WORKING
}
return true;
} else {
return false;
}
}
最佳答案
线索就在您正在实现的委托(delegate)方法的名称中:shouldReplaceCharactersInRange
。
您正在重写它,就像它是 didReplaceCharactersInRange
一样。
字符的替换不会发生,直到您从此方法返回之后(如果有的话)(取决于返回值)。
如果您想在此方法中自行更改文本,则应从该方法返回 false
。
编辑: 如果返回 false,文本不会自动更改。
您当前在 textField 的文本后面附加了一个问号,但不添加用户尝试输入的字符。
您可能想让它更像:
textField.text! = 文本 + '?'
本质上,您希望在每次调用此方法时手动将 textField
的文本设置为正确的字符串。
关于ios - 键入时将字符附加到文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37207909/