快速验证文本字段 3 [英] Validate text fields swift 3
本文介绍了快速验证文本字段 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将所有文本字段设为必填字段,以确保用户不会将其留空.我试过这个,但由于某种原因它不起作用.我觉得我的逻辑是正确的,但这是swift逻辑的问题
I am trying to make all of my text fields required to make sure that users does not leave it empty. I tried this but for some reason it's not working. I feel like my logic is correct, but it's an issue with swift's logic
这是我的代码:
let title = txtTitle.text!
let location = txtWhere.text!
let when = txtWhen.text!
if title != nil && location != nil && when != nil {
var titleArray = [String]()
var whereArray = [String]()
var whenArray = [String]()
let titleObject = UserDefaults.standard.object(forKey: "saveTitle")
let whereObject = UserDefaults.standard.object(forKey: "saveLocation")
let whenObject = UserDefaults.standard.object(forKey: "saveWhen")
if let tempTitle = titleObject as? [String] {
titleArray = tempTitle
titleArray.append(txtTitle.text!)
print(titleArray)
}
else {
titleArray = [txtTitle.text!]
}
if let tempWhere = whereObject as? [String] {
whereArray = tempWhere
whereArray.append(txtWhere.text!)
//print(titleArray)
}
else {
whereArray = [txtWhere.text!]
}
if let tempWhen = whenObject as? [String] {
whenArray = tempWhen
whenArray.append(txtWhen.text!)
//print(titleArray)
}
else {
whenArray = [txtWhen.text!]
}
UserDefaults.standard.set(titleArray, forKey: "saveTitle")
UserDefaults.standard.set(whereArray, forKey: "saveLocation")
UserDefaults.standard.set(whenArray, forKey: "saveWhen")
txtTitle.text = ""
txtWhere.text = ""
txtWhen.text = ""
txtTime.text = ""
}
else
{
errMsg.isHidden = false
errMsg.text = "All fields are required"
}
}
推荐答案
要可靠地检查文本字段的 text
属性是否不是 nil
并且不是空的,请使用
To check reliably if the text
properties of the text fields are not nil
and not empty use
if let title = txtTitle.text, !title.isEmpty,
let location = txtWhere.text, !location.isEmpty,
let when = txtWhen.text, !when.isEmpty { ...
如果所有条件都通过,则三个变量将被安全解包.
If all conditions are passed the three variables are safely unwrapped.
这篇关于快速验证文本字段 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文