skip to Main Content

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


  1. I think you’re missing a test:
    Instead of

    if tfConfirmPasswordText.isEmpty
    

    I would have write

    if tfConfirmPasswordText.isEmpty || tfpasswordText.isEmpty
    
    Login or Signup to reply.
  2. Instead of using shouldChangeCharactersIn ,i used like below to make it works

        override func viewDidLoad() {
                super.viewDidLoad()
              //initially at disabled 
                disabledButton()
                [tfPassword, tfConfirmPasswordText].forEach({ $0.addTarget(self, action: #selector(textFieldEditingDidChange), for: .editingChanged) })
            }
            
            @objc func textFieldEditingDidChange(sender: UITextField) {
                
                guard
                    let tfPasswordTxtValue = tfPassword.text, !tfPasswordTxtValue.isEmpty,
                    let tfConfirmPasswordTextValue = tfConfirmPasswordText.text, !tfConfirmPasswordTextValue.isEmpty
                        
                else {
                    disabledButton()
                    return
                }
                enableButton()
                
            }
    
         func disabledButton(){
          btnContinue.backgroundColor = UIColor(named: "labelColor")
          btnContinue.isEnabled = false
         }
    
        func enableButton(){
         btnContinue.isEnabled = true
       }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search