I want to enable and change color of a button depending on text in password and confirm password textfields. So I found this code online:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let tfConfirmPasswordText = (tfConfirmPassword.text! as NSString).replacingCharacters(in: range, with: string)
if tfConfirmPasswordText.isEmpty {
btnContinue.backgroundColor = UIColor(named: "labelColor")
btnContinue.isEnabled = false
}
else if tfPassword.text != "" && !tfConfirmPasswordText.isEmpty {
btnContinue.backgroundColor = UIColor(named: "accentColor")
btnContinue.isEnabled = true
}
return true
}
This code does work and using these conditions it will enable or disable continue button according to confirmPassword
textfield.
But the problem is that after filling both password
and confirmPassword
textfields, if I remove text from password
field it still keeps the button enabled and only disables it if text is removed from confirmPassword
textfield.
And if I put password.delegate = self
alongside confirmPassword.delgate = self
in viewDidLoafd()
, it crashes when I put more than 1 character in any textfield.
Is there any way to enable or disable button by always keeping a check on both the textfields instead of just one..ie. confirmPassword textfield?
2
Answers
I think you’re missing a test:
Instead of
I would have write
Instead of using shouldChangeCharactersIn ,i used like below to make it works