检查字段是否为空不起作用

时间:2018-08-28 05:21:09

标签: ios swift ibaction hud

我似乎对此代码有麻烦。尝试运行检查以确保字段包含文本。如果字段中没有文本,则应该显示带有文本“电子邮件/密码不能为空”的HUD。它似乎忽略了检查,直接进入尝试登录。当我删除强制展开时,它会停止并执行检查,但是如果字段中有文本,则不会前进到HUD消息“登录”

@IBAction func logInDidTapped(_ sender: Any) {
    guard let email = emailTxtField.text, !email.isEmpty,
    let password = passwordTxtField.text, !password.isEmpty else {
        SVProgressHUD.showError(withStatus: "Email/Password Can't Be Empty")
        return
    }
    SVProgressHUD.show(withStatus: "Signing In...")
}

2 个答案:

答案 0 :(得分:1)

使您的检查像下面这样简单,以检查UITextfield是否包含文本:

if emailTxtField.text == "" || passwordTxtField.text == "" {
    SVProgressHUD.showError(withStatus: "Email/Password Can't Be Empty")
    return
}

SVProgressHUD.show(withStatus: "Signing In...")

希望这对您有所帮助。

答案 1 :(得分:0)

您不需要使用防护,因为emailTxtField.text/passwordTxtField.text如果为空则返回为""

要获得准确的结果,请检查count中的文本。

@IBAction func logInDidTapped(_ sender: Any) {

    if let email = emailTxtField.text,
        let password = passwordTxtField.text {

        if email.count > 0 && password.count > 0 {

            SVProgressHUD.show(withStatus: "Signing In...")
        } else {

            SVProgressHUD.showError(withStatus: "Email/Password Can't Be Empty")
        }
    }
}