检查文本字段是否为空 Swift [英] Checking if textfields are empty Swift
问题描述
我知道有大量堆栈溢出页面解释了如何执行此操作,但是每次我从此处获取代码并将其放入时,我都会遇到相同的错误,并且该错误是字符串"的值?没有成员文本" 任何可以快速检查文本字段是否为空的可靠方法的想法?
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;
}
推荐答案
这篇文章 给出了很好的答案(这是一个可惜它没有已接受"标记).使用 (self.field.text?.isEmpty ?? true)
.
This post is given a good answer (it's a pity it has no "accepted" mark). Use (self.field.text?.isEmpty ?? true)
.
假设您的 textField
声明为:
@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;
}
或:
// Check for empty fields
if userEmailTextField.text?.isEmpty ?? true {
// Display alert message
return;
}
这篇关于检查文本字段是否为空 Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!