首页 > 解决方案 > 如果语句在 Swift 4 中的行为不符合预期

问题描述

我正在尝试编写一个 if 语句来检查用户是否在用户名和密码字段中输入了任何内容。如果两个字段中都有任何字符,我们设置:

self.loginButton.isEnabled = true
self.loginButton.layer.opacity = 1

如果不是,我们将第一个设置为 false,将第二个设置为 0.2。

这是我的代码:

if self.emailTextField.text!.isEmpty || self.passwordTextField.text!.isEmpty
    {
        self.loginButton.isEnabled = false
        self.loginButton.layer.opacity = 0.2
    }
    else if self.emailTextField.text!.isEmpty == false || self.passwordTextField.text!.isEmpty == false
    {
        self.loginButton.isEnabled = true
        self.loginButton.layer.opacity = 1
    }

当我运行应用程序时,无论我在文本字段中输入什么,按钮都将始终处于非活动状态并设置为 0.2 不透明度。我怎样才能解决这个问题?

标签: swiftif-statement

解决方案


您可能认为您的代码正在观察文本字段文本的变化,但事实并非如此

// inside viewDidLoad
 emailTextField.addTarget(self, action: #selector(self.textChanges(_:)), for: UIControl.Event.editingChanged)
 passwordTextField.addTarget(self, action: #selector(self.textChanges(_:)), for: UIControl.Event.editingChanged)

并在此处获取更改

@objc func textChanges(_ textField: UITextField) {
  changed()
}  
func changed() { 
    if self.emailTextField.text!.isEmpty || self.passwordTextField.text!.isEmpty
    {
        self.loginButton.isEnabled = false
        self.loginButton.layer.opacity = 0.2
    }
    else  
    {
        self.loginButton.isEnabled = true
        self.loginButton.layer.opacity = 1
    } 
}

推荐阅读