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

时间:2018-09-10 02:11:12

标签: swift uibutton uitextfield isenabled disable

我正在尝试禁用登录按钮,直到电子邮件和密码textField都至少包含一个字符为止。我尝试查找不同的答案,但是在我可以解决的答案上,代码似乎已过时。我也不知道如何观察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

}



}

1 个答案:

答案 0 :(得分: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
        }
    }
}