0

我正在尝试禁用登录按钮,直到电子邮件和密码文本字段中都至少包含一个字符。我尝试查找不同的答案,但对于我可以接受的答案,代码似乎已经过时。我也不知道如何观察 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

}



}
4

1 回答 1

1

像这样使用属性观察器。

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
        }
    }
}
于 2018-09-10T02:20:34.700 回答