首页 > 解决方案 > 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 : ""

有什么建议么?

标签: iosswiftuitextfield

解决方案


斯威夫特 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
}

推荐阅读