我想检查我的 UITextFields
的 .text
状态。在 != ""
上执行函数并显示警告 View if == ""
。因为我有 5 个不同的 UITextFields
,所以我想到了一个 switch
语句。
@IBAction func doneButton(_ sender: Any) {
let indexPath = IndexPath(row: 0, section: 0)
let cell = self.tableView.cellForRow(at: indexPath) as! SetupCell
var textFields: [UITextField] = []
textFields = [cell.nameTF,
cell.townTF,
cell.birthdayTF,
cell.genreTF,
cell.deejayTF]
for tf in textFields {
print("called") // is printed
if tf.text != "" {
print("not empty") // is printed
switch UITextField() {
case cell.nameTF:
saveCredential(ME, "name", cell.nameTF.text!)
case cell.birthdayTF:
saveCredential(ME, "birthday", cell.birthdayTF.text!)
case cell.townTF:
saveCredential(ME, "town", cell.townTF.text!)
case cell.deejayTF:
saveCredential(ME, "deejayName", cell.deejayTF.text!)
case cell.genreTF:
saveCredential(ME, "genre", cell.genreTF.text!)
default:
break
}
} else {
print("is empty") // printed
switch UITextField() {
case cell.nameTF:
presentAlertView(self, title: "Error", message: "Name missing")
case cell.birthdayTF:
presentAlertView(self, title: "Error", message: "Birthday missing")
case cell.townTF:
presentAlertView(self, title: "Error", message: "Town missing")
case cell.deejayTF:
presentAlertView(self, title: "Error", message: "Deejay name missing")
case cell.genreTF:
presentAlertView(self, title: "Error", message: "Genre missing")
default:
break
}
}
}
}
但是 switch
语句中的代码没有被执行。如果为空,则为空,否则为空。我相信问题可能出在 switch UITextField()
中,但我找不到解决方案。我错过了什么?非常感谢您的帮助。
附言。 saveCredential
以及 presentAlertView
在应用程序的其他部分上运行良好,因此这可能不是问题所在。但可以肯定的是:
func presentAlertView(_ vc: UIViewController, title: String, message: String?) {
var alert = UIAlertController(title: title, message: nil, preferredStyle: UIAlertControllerStyle.alert)
if message != nil {
alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
}
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
vc.present(alert, animated: true, completion: nil)
}
最佳答案
问题是您使用 switch
语句传递 UITextFiled
的新实例,而不是传递来自 Array
的对象。
switch tf {
代替
switch UITextField() {
关于ios - 如何在 Swift 3 中使用 UITextFields 创建开关表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40434803/