我是快速编程语言的初学者。我正在寻找替代方法来检查我的所有文本字段。我想做的是。如果文本字段没有任何值。将文本字段文本更改为红色文本字段名称并向用户发送警报。如果用户开始将机会文本颜色键入黑色。
这是我的方法,但我认为这不是正确的方法。
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)
}
}
答案 0 :(得分:0)
我建议通过获取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)
}