Search code examples
swiftuitextfieldtextfielddisable

Disabling button when textfield is empty wait for any change in other textfield


I wanna disable log in button if email or password textfield is empty and enable it again when both are filled so i use the below code:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if txtEmail.text != "" , txtPassword.text != "" {
        btnLogInOutlet.isEnabled = true
    }else if txtEmail.text! == "" || txtPassword.text! == "" {
        btnLogInOutlet.isEnabled = false
    }
    return true
}

The problem appears when i type in both fields then i delete what i type in one of those fields . As you can see in the picture below , the button still enabled.It only become disabled again if i start editing in the other (not empty) textfield.

enter image description here

My question is How to disable the button again directly after i delete what i type in any textfield before i move to another one??


Solution

  • You are getting the text value from your textfield before returning true from your delegate - it means that it has old value, before the change.

    Instead of using shouldChangeCharactersIn delegate method, use the action (you can also hook it up using storyboards):

    txtEmail.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged)
    txtPassword.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged)
    

    Now in textFieldDidChange(textField: UITextField) method you can copy paste your implementation (slightly improved here):

    @objc func textFieldDidChange(textField: UITextField) {
       btnLogInOutlet.isEnabled = !txtEmail.text.isEmpty && !txtPassword.text.isEmpty
    }