问题
I am using MVVM Structure and when textfield value changed update the view model.
Everything working fine except password field
Here is code
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
}
as password filed cleared when backspace (or delete button) tapped from keyboard newText
is returning previously set value not empty string.
issue: when password field is clear still newText
has string
When I try to see range returned by function it not looks valid
po range expression produced error: error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=10, address=0x107a2b000). The process has been returned to the state before expression evaluation.
I know I can do it textField.clearsOnBeginEditing = false;
but I want it to be clear as default functionality.
Please help me Thanks in advance
回答1:
textField:shouldChangeCharactersInRange:replacementString:
is called before text on textField is changed so it's not right place to do these works.
We have another way to check text changed and I think it can resolve your problem.
txtOldPassword.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged)
txtNewPassword.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged)
txtConfirmPassword.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged)
@objc func textFieldDidChange(textField: UITextField) -> Void {
if let text = textField.text {
if textField == txtOldPassword {
changePasswordViewModel.updateOldPassword(string: text)
} else if textField == txtNewPassword {
changePasswordViewModel.updateNewPassword(string: text)
} else if textField == txtConfirmPassword {
changePasswordViewModel.updateConfirmPassword(string: text)
}
}
}
textFieldDidChange(textField:)
will be called after text is changed.
来源:https://stackoverflow.com/questions/50266486/textfield-shouldchangecharactersin-for-password-field-clear