【问题标题】:Textfield shouldChangeCharactersIn for password field clear用于清除密码字段的文本字段 shouldChangeCharactersIn
【发布时间】: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


【解决方案1】:

textField:shouldChangeCharactersInRange:replacementString: 在 textField 上的文本更改之前被调用,所以它不是做这些工作的正确位置。

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

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

【讨论】:

  • 抱歉,我刚刚复制了你的代码。感谢您纠正我的回答。
  • 工作正常!!感谢您的努力接受和支持
  • 欢迎我的朋友!
猜你喜欢
  • 2019-01-23
  • 1970-01-01
  • 2015-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多