Textfield shouldChangeCharactersIn用于密码字段清除

时间:2018-05-10 06:03:33

标签: ios swift uitextfield swift4 uitextfielddelegate

我正在使用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)。   该过程已返回到表达式评估之前的状态。

enter image description here

我知道我可以做textField.clearsOnBeginEditing = false;,但我希望它能作为默认功能明确。

请提前帮助我

1 个答案:

答案 0 :(得分:2)

在更改textField上的文字之前调用

textField:shouldChangeCharactersInRange:replacementString:,因此它不适合执行这些工作。

我们还有另一种方法来检查更改后的文字,我认为它可以解决您的问题。

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:)将在文本更改后调用。