【问题标题】:Elegant way to check if UITextField is empty [duplicate]检查 UITextField 是否为空的优雅方法 [重复]
【发布时间】:2018-09-02 17:14:03
【问题描述】:

我目前正在从事一个使用大量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
}

有没有更快的方法不用解开文本字段的文本属性来判断它是否为空?

谢谢!

【问题讨论】:

标签: ios swift validation uitextfield


【解决方案1】:

如何扩展UITextField...

extension UITextField {

    var isEmpty: Bool {   
        if let text = textField.text, !text.isEmpty {
             return false
        } 
        return true
    }
}

那么……

if myTextField.isEmpty {
}

【讨论】:

【解决方案2】:

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

if textField.hasText {
    // Text field is not empty
} else {
    // Text field is empty
}

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

extension UITextField {
    var isEmpty: Bool {
        return text?.trimmingCharacters(in: .whitespacesAndNewlines) == ""
    }
}

let tf = UITextField()
tf.text = " \n \n "
tf.isEmpty   // true

【讨论】:

  • textfield.text = " "; print(textfield.hasText) 返回true
  • 空格被视为文本。如果需要检查,可以修剪空格
  • 是的,这就是我的观点。
【解决方案3】:

如果您有多个文本字段要检查,您可以将它们全部放在一个保护语句中

guard let text1 = textField1.text, let text2 = textField2.text, let text3 = textField3.text, !text1.isEmpty, !text2.isEmpty, !text3.isEmpty else {
    //error handling
    return
}

//Do stuff

【讨论】:

  • 这是一个不错的方法
【解决方案4】:

我喜欢验证每个文本字段取决于用户应该提供的内容,emailTextField 应该包含一个有效的电子邮件地址等。虽然Ashley Mills 回答很方便,但如果您将空格 " " 视为文本,这将返回 false。

在您的情况下,既然您需要以相同的方式验证多个文本字段,为什么不扩展 UITextField 就像 Ashley 使用可以验证作为数组传递的每个文本字段的静态类方法所做的那样,除此之外还有每种文本字段的其他验证方法。我学会了使用 guard 而不是返回布尔值。这样guard let可以用来检查验证是否失败(为nil)并执行正确的代码,例如向用户显示提示,或者继续执行。

UITextFieldExtension.swift

import Foundation
import UIKit

extension UITextField {

    /// Validates all text field are non-nil and non-empty, Returns true if all fields pass.
    /// - Returns: Bool
    static func validateAll(textFields:[UITextField]) -> Bool {
        // Check each field for nil and not empty.
        for field in textFields {
            // Remove space and new lines while unwrapping.
            guard let fieldText = field.text?.trimmingCharacters(in: .whitespacesAndNewlines) else {
                return false
            }
            // Are there no other charaters?
            if (fieldText.isEmpty) {
                return false
            }

        }
        // All fields passed.
        return true
    }


    //A function that validates the email address...
    func validateEmail(field: UITextField) -> String? {
        guard let trimmedText = field.text?.trimmingCharacters(in: .whitespacesAndNewlines) else {
            return nil
        }

        //email addresses are automatically detected as links in i0S...
        guard let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
            return nil
        }

        let range = NSMakeRange(0, NSString(string: trimmedText).length)
        let allMatches = dataDetector.matches(in: trimmedText,
                                              options: [],
                                              range: range)

        if allMatches.count == 1,
            allMatches.first?.url?.absoluteString.contains("mailto:") == true
        {
            return trimmedText
        }
        return nil
    }

    func validateUserName(field: UITextField) -> String? {

        guard let text:String = field.text else {
            return nil
        }

        /* 3 to 12 characters, no numbers or special characters */
        let RegEx = "^[^\\d!@#£$%^&*<>()/\\\\~\\[\\]\\{\\}\\?\\_\\.\\`\\'\\,\\:\\;|\"+=-]+$"
        let Test = NSPredicate(format:"SELF MATCHES %@", RegEx)
        let isValid = Test.evaluate(with: text)

        if (isValid) {
            return text
        }

        return nil
    }

    /*6 to 16 Characters */
    func validatePassword(field: UITextField) -> String?{
        guard let text:String = field.text else {
            return nil
        }
        /*6-16 charaters, and at least one number*/
        let RegEx = "^(?=.*\\d)(.+){6,16}$"
        let Test = NSPredicate(format:"SELF MATCHES%@", RegEx)
        let isValid = Test.evaluate(with: text)

        if (isValid) {
            return text
        }

        return nil

    }
}

同时,其他地方...

if (UITextField.validateAll(textFields: [emailTextField, nameTextField])) {
    // Do something
}

【讨论】:

    猜你喜欢
    • 2014-07-11
    • 2011-03-28
    • 1970-01-01
    • 2020-08-11
    • 2013-09-11
    • 2015-07-14
    • 2023-03-15
    • 1970-01-01
    • 2013-09-07
    相关资源
    最近更新 更多