Textfield 甚至是空的,但在 Swift 中不认为是空的



我有一些多个文本字段,如果所有字段都已填充,那么只有我必须调用一些方法,否则我必须抛出警报。

但是,即使文本字段为空,它的执行条件也为 false。

if genderTextField.text?.isEmpty == true && weightTextField.text?.isEmpty == true && heightTextField.text?.isEmpty == true {
self.showAlert(withTitle:"Title", withMessage: "Fill all the fields")
} else {
//call some function
}

但是,如果我打印文本字段文本

po genderTextField.text
▿ Optional<String>
- some : ""

有什么建议吗?

Swift 5.2

一种更优雅的方法是在UITextField上创建一个扩展

extension UITextField {
var isEmpty: Bool {
if let text = self.text, !text.isEmpty {
return false
} else {
return true
}
}
}

然后你像这样检查:

if genderTextField.isEmpty || weightTextField.isEmpty || heightTextField.isEmpty {
showAlert()
} else {
// do something else
}

最新更新