簡體   English   中英

如何交替檢查所有uitextfields?

[英]How to alternatively check all uitextfields in swift?

我是快速編程語言的初學者。 我正在尋找檢查我所有文本字段的替代方法。 我想做的是。 如果文本字段沒有任何值,請將文本字段文本更改為紅色文本字段名稱並向用戶發送警報。 如果用戶開始輸入機會文本,則顏色會變回黑色。

這是我的方法,但我認為這不是正確的方法。

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)

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM