如何在 swift 中交替检查所有 uitextfields?

How to alternatively check all uitextfields in swift?

我是 swift 编程语言的初学者。我正在寻找替代方法来检查我所有的文本字段。我想做的是。如果文本字段没有任何 value.Change 文本字段文本到红色文本字段名称并向用户发送警报。如果用户开始键入,则文本颜色有可能变回黑色。

这是我的方法,但我不认为这是正确的方法。

func alertMessage(title:String, message:String)->Void{

    var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

    self.presentViewController(alert, animated: true, completion: nil)

}

func checkAllFields()->Void{



    var allFields=[String:String]()
    var fieldCounter = 0


    allFields = ["Username":userNameField.text,"Name":nameField.text,"Surname":surNameField.text,"Email":emailField.text, "Password":passwordField.text]

    for (field, fieldData) in allFields{

        if fieldData.isEmpty{

            fieldCounter++
        }

    }

    if fieldCounter <= allFields.count{

        var title = "Missing Fields"
        var message = "You need to fill all fields."

        if userNameField.text.isEmpty{

            userNameField.textColor = UIColor.redColor()
            userNameField.text = "Username"

        }

        if nameField.text.isEmpty{

            nameField.textColor = UIColor.redColor()
            nameField.text = "Name"


        }

        if surNameField.text.isEmpty{

            surNameField.textColor = UIColor.redColor()
            surNameField.text = "Surname"

        }

        if emailField.text.isEmpty {

        emailField.textColor = UIColor.redColor()
        emailField.text = "Email"

        }

        if passwordField.text.isEmpty  {

        passwordField.textColor = UIColor.redColor()
        passwordField.text = "Password"

        }

        if retypePasswordField.text.isEmpty{
        retypePasswordField.textColor = UIColor.redColor()
        retypePasswordField.text = "Retype Password"
        }

        alertMessage(title, message: message)



    }



}

我建议通过获取 UITextView 而不是其内容来简化代码:

func checkAllFields()->Void{

var allFields=[String:UITextView]()
var fieldCounter = 0


allFields = ["Username":userNameField, "Name":nameField, "Surname":surNameField, "Email":emailField, "Password":passwordField]

for (fieldName, fieldTextView) in allFields{

    if fieldTextView.text.isEmpty{
        fieldTextView.textColor = UIColor.redColor()
        fieldTextView.text = fieldName
        fieldCounter++

    }

}

if fieldCounter > 0 {

    var title = "Missing Fields"
    var message = "You need to fill all fields."

    alertMessage(title, message: message)

}