下面是代码,如果userNameTF或passwordTF已满或为空,则会显示警告。
@IBAction func LoginBtn(sender: AnyObject) {
let userName = userNameTF.text
let password = passwordTF.text
if ((userName?.isEmpty) != nil) {
displayMyAlertMessage ("Forget to fill your user name")
return
}
if ((password?.isEmpty) != nil){
displayMyAlertMessage ("Forget to fill your password")
return
}
}
func displayMyAlertMessage(userMessage:String){
let myAlert = UIAlertController(title: "WOF", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
myAlert.addAction(okAction)
self.presentViewController(myAlert, animated: true, completion: nil)
}
答案 0 :(得分:1)
您只需使用我的代码检查您的代码即可。你检查的价值是空的还是没有错误。
按照以下步骤操作:
1。)为文本字段定义IBOutlet
@IBOutlet var userNameTF : UITextField!
@IBOutlet var passwordTF : UITextField!
2。)在点击按钮的事件上写下以下代码。
let userName = userNameTF.text
let password = passwordTF.text
if (userName!.isEmpty)
{
displayMyAlertMessage ("Forget to fill your user name")
return
}
else if (password!.isEmpty)
{
displayMyAlertMessage ("Forget to fill your password")
return
}
else
{
// Do Whatever u want.
}
享受编码......工作正常。
答案 1 :(得分:1)
这是使用guard
@IBAction func LoginBtn(sender: AnyObject) {
guard let userName = userNameTF.text where !userName.isEmpty else {
displayMyAlertMessage ("Forget to fill your user name")
return
}
guard let password = passwordTF.text where !password.isEmpty else {
displayMyAlertMessage ("Forget to fill your password")
return
}
// do something with userName and password
}