【发布时间】:2018-05-10 06:03:33
【问题描述】:
我正在使用 MVVM 结构,当文本字段值更改时更新视图模型。
除密码字段外一切正常
这里是代码
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text,
let range = Range.init(range, in: text) {
let newText = text.replacingCharacters(in: range, with: string)
if textField == txtOldPassword {
changePasswordViewModel.updateOldPassword(string: newText)
} else if textField == txtNewPassword {
changePasswordViewModel.updateNewPassword(string: newText)
} else if textField == txtConfirmPassword {
changePasswordViewModel.updateConfirmPassword(string: newText)
}
}
return true
}
当从键盘上点击退格(或删除按钮)newText 时,密码字段被清除,返回先前设置的值而不是空字符串。
问题:当密码字段被清除时,newText 仍有字符串
当我尝试查看函数返回的范围时,它看起来无效
po 范围 表达式产生错误:错误:执行被中断,原因:EXC_BAD_ACCESS(代码=10,地址=0x107a2b000)。 进程已经返回到表达式求值前的状态。
我知道我可以做到textField.clearsOnBeginEditing = false;,但我希望它作为默认功能明确。
请帮助我提前谢谢
【问题讨论】:
-
如您所说,
newText返回先前设置的值是因为您使用textField.text而不是string参数进行检查。textField.text将在文本字段中返回可用值,string将返回将要添加的值。此委托方法在文本字段发生任何更改之前执行 -
@Priya 感谢您的回复。如您所知,如果您观察到
text.replacingCharacters(in: range, with: string),范围将返回用户在文本字段中修改的字符串区域,我正在用范围替换当前文本中的字符串。它在除密码字段之外的所有情况下都有效 -
@Priya As 当您重新关注文本字段并按返回或删除按钮时,整个文本将被清除,因此在这种情况下它不起作用!
标签: ios swift uitextfield swift4 uitextfielddelegate