Search code examples
swiftuibuttonuitextfieldisenableddisable

How can I disable button until both textFields have at least one character in them?


I am trying to disable a login button until both email and password textFields have at least one character in both of them. I tried looking up different answers but the code seems to be outdated on the answers I could fine. I also do not know how to observe the TextFields values to see if there is change. Can someone please assist me or point me in the right direction?

This is the count I currently have.

func viewDidLoad() {
super.viewDidLoad()
// Setting text field delegates

emailTextField.delegate = self

passwordTextField.delegate = self

//checking if both textFields are filled in to enable Login Button

if (emailTextField.text?.count)! > 0  && (passwordTextField.text?.count)! > 0    {

loginButton.isEnabled = true
loginButton.alpha = 0.55

} else {
    loginButton.isEnabled = false
    loginButton.alpha = 0.32

}



}

Solution

  • Use property observer like this.

    var testfield: UITextField? {
        didSet{
    
            print("Called after setting the new value")
            if let name = testfield?.text, name.count > 0 {
                print("New name is \(name) and old name is \(String(describing: oldValue?.text))")
                testfield?.isEnabled = true
            } else {
                //dont have text
                testfield?.isEnabled = false
            }
        }
        willSet(myNewValue) {
    
            print("Called before setting the new value")
            if let newName = myNewValue?.text, newName.count > 0 {
                print("New name is \(newName)")
                testfield?.isEnabled = true
    
            } else {
                //dont have text
                testfield?.isEnabled = false
            }
        }
    }