【问题标题】:Textfield is even empty but not considering as empty in SwiftTextfield 甚至是空的,但在 Swift 中不认为是空的
【发布时间】:2020-05-12 10:18:56
【问题描述】:

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

但是,即使文本字段为空,执行条件为假。

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 : ""

有什么建议吗?

【问题讨论】:

  • 如果你想检查是否所有的TextFields都被填满,你应该使用OR
  • 你的逻辑一开始就错了。 - 你想要||(或)不想要 - 如果任何字段为空,你想要警报。您也可以省略 == true,因为 isEmpty 是一个布尔值。我建议您通过零合并运算符 if (genderTextField.text ?? "").isEmpty ... 正确处理 nil

标签: ios swift uitextfield


【解决方案1】:

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
}

【讨论】:

    猜你喜欢
    • 2017-02-15
    • 1970-01-01
    • 2023-03-13
    • 2020-02-23
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多