我有多个文本字段,并且如果所有字段都被填充,那么只有我必须调用某些方法,否则我必须发出警报。
但是,即使文本字段为空,其执行条件也为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
}
如果要在UITextField
上创建扩展名,也可以使用它来使UI更加明显...