ios - Textfield 甚至是空的,但在 Swift 中不认为是空的
问题描述
我有一些多个文本字段,如果所有字段都已填满,那么我只需调用一些方法,否则我必须发出警报。
但是,即使文本字段是空的,它的执行条件也是错误的。
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 : ""
有什么建议么?
解决方案
斯威夫特 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
}
推荐阅读
- c# - Unity Quaternion - 获取组件 B 相对于组件 A 的欧拉角
- scala - spark scala中结构数组的情况下如何更新列值
- php - 如何检测共享主机/实时服务器中的错误?
- scala - 如何创建地图
和地图 protobuf 斯卡拉 - javascript - 有没有一种可能的方法来检查函数中的第二个括号?
- java - 为什么 Windows 搜索工具栏中不使用 jpackage 图标?
- java - 调用 System.arrayCopy 时是否固定内存
- php - SQLSTATE [42000]:语法错误或访问冲突:1067 'fechaNacimiento' 的默认值无效 - laravel
- flutter - 如何自动生成以下格式的多个按钮
- windows - 在 VS_FIXEDFILEINFO 中获取错误的文件版本