Checking if textfields are empty Swift

巧了我就是萌 提交于 2019-11-27 02:01:27

问题


I know there are tons of stack overflow pages out there that explain how to do this but everytime I take the code from here and put it in i get the same error and that error is value of "string?" has no member "text" Any ideas of a solid way that will work for checking if a textfield is empty in swift?

let userEmail = userEmailTextField.text;
// Check for empty fields
if (userEmail.text.isEmpty) {
    // Display alert message
    return;
}

回答1:


This post is given a good answer (it's a pity it has no "accepted" mark). Use (self.field.text?.isEmpty ?? true).

Assume your textField is declared as:

    @IBOutlet weak var textField: UITextField!

You can check its emptiness with:

    if textField.text?.isEmpty ?? true {
        print("textField is empty")
    } else {
        print("textField has some text")
    }

To use the variables in your edited post:

    let userEmail = userEmailTextField.text;
    // Check for empty fields
    if userEmail?.isEmpty ?? true {
        // Display alert message
        return;
    }

or:

    // Check for empty fields
    if userEmailTextField.text?.isEmpty ?? true {
        // Display alert message
        return;
    }



回答2:


The text property is an optional. So it can contains a String or nil.

If you want to treat nil as an empty String then just write

let isEmpty = (textField.text ?? "").isEmpty



回答3:


Alternatively you can also use:

Swift 3:

if (textField.text.characters.count > 0) {
   print("text field not empty")
} else {
   print("text field empty")
}

Swift 4.x and above:

if (textField.text.count > 0) {
       print("text field not empty")
    } else {
       print("text field empty")
    }



回答4:


Give you an example picture and cover code.

@IBAction func save(_ sender: Any) {
    print("Saving...")
    //CHECK MANDATORY FIELDS
    checkMandatoryFields()
}

private func checkMandatoryFields(){

    //CHECK EMPTY FIELDS
    if let type = typeOutle.text, let name = nameOutlet.text, let address = addressOutlet.text, type.isEmpty || name.isEmpty || address.isEmpty {
        print("Mandatory fields are: ")
        errorDisplay(error: "Mandatory fields are: Type, Name, Address.")
        return
    }

    //CHECK SPACE ONLY FIELDS
}




回答5:


Here's the correct answer for this.

textField.text = ""
if (textField.text.isEmpty) {
    print("Ooops, it's empty")
}



回答6:


It was this check that helped me since it was necessary for me to send a request to the API, and it was necessary to send nill instead of "" if the textField is without text.

textField.text!.count > 0  ? textField.text : nil

Alternatively, you can check this way (but this option did not fit me):

if textField.text != nil {

} else {

}


来源:https://stackoverflow.com/questions/38162602/checking-if-textfields-are-empty-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!