在两个文本字段中至少有一个字符之前,如何禁用按钮?

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

我正在尝试禁用登录按钮,直到电子邮件和密码文本字段都至少有一个字符。我尝试查找不同的答案,但代码似乎已经过时了,我可以很好地回答。我也不知道如何观察 TextFields 值以查看是否有变化。有人可以帮助我或指出正确的方向吗?

这是我目前的计数。

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

}



}

像这样使用 属性 观察者。

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
        }
    }
}