Home > Net >  check all textfields simultaneously & only enable button if they have text
check all textfields simultaneously & only enable button if they have text

Time:11-25

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?

CodePudding user response:

I think you're missing a test: Instead of

if tfConfirmPasswordText.isEmpty

I would have write

if tfConfirmPasswordText.isEmpty || tfpasswordText.isEmpty

CodePudding user response:

Instead of using shouldChangeCharactersIn ,i used like below to make it works

    override func viewDidLoad() {
            super.viewDidLoad()
          //initially at disabled 
            button.alpha = 0.2
            [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 {
                button.alpha = 0.2
                return
            }
            button.alpha = 1
            
        }
  • Related