Swift 在文本输入期间验证 2 uitextfield 密码

Swift validate 2 uitextfield password during text entry

我有 2 个文本字段,其中包含 1 个输入引脚和 1 个重新输入引脚,我尝试使用 shouldChangeCharactersIn 进行验证,因此如果引脚不相同,它会自动显示一条小文本消息,表示引脚不相同。很好,但效果不佳,因为如果我只在输入引脚中键入 6 针,并且我还在重新输入引脚中键入 6 针,(在这种情况下,我故意输入错误的针)并且消息不会弹出,但是如果我输入超过 6 次,比如说 7 号,那么消息就会出现,为什么我不明白。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    

    if textConfirmPIN.text!.count == 6 && textPIN.text!.count == 6 {
        if textConfirmPIN.text != textPIN.text{
            self.showError(message: "PIN is not the same")
        }
    }

    return true
}

抱歉我的英语不好,但是谁能告诉我发生了什么事?谢谢大家

使用文本字段编辑更改事件而不是 shouldChangeCharactersIn,因为当您在 shouldChangeCharactersIn 中检查 textConfirmPIN.text!.count 时,最后键入的字符仍然不存在,直到 return true

这就是它在您键入第 7 个字符时调用的原因