检查 UITextField 是否为空的优雅方法

Lar*_*sen 3 validation uitextfield ios swift

我目前正在做一个使用大量UITextFields的项目。为了验证,我需要检查UITextFields 是否为空。我有一个可行的解决方案,但它不是那么优雅。也许有人知道更好的方法。

这是我的解决方案:

// Check if text field is empty
if let text = textField.text, !text.isEmpty {
     // Text field is not empty
} else {
     // Text field is empty
}
Run Code Online (Sandbox Code Playgroud)

有没有更快的方法而不展开文本字段的文本属性来确定它是否为空?

谢谢!

Ash*_*lls 6

怎么延长UITextField...

extension UITextField {

    var isEmpty: Bool {   
        if let text = textField.text, !text.isEmpty {
             return false
        } 
        return true
    }
}
Run Code Online (Sandbox Code Playgroud)

那么……

if myTextField.isEmpty {
}
Run Code Online (Sandbox Code Playgroud)

  • /sf/answers/3031576831/ 上更短的解决方案:`return text?.isEmpty ?? 真的` (4认同)
  • https://developer.apple.com/documentation/uikit/uikeyinput/1614457-hastext (3认同)

Leo*_*bus 5

您可以使用UIKeyInput属性hasText。它适用于 UITextField 和 UITextView:

if textField.hasText {
    // Text field is not empty
} else {
    // Text field is empty
}
Run Code Online (Sandbox Code Playgroud)

如果您想检查文本上是否不仅有空格:

extension UITextField {
    var isEmpty: Bool {
        return text?.trimmingCharacters(in: .whitespacesAndNewlines) == ""
    }
}
Run Code Online (Sandbox Code Playgroud)
let tf = UITextField()
tf.text = " \n \n "
tf.isEmpty   // true
Run Code Online (Sandbox Code Playgroud)