当UITextField已满或为空时,显示警报Swift

时间:2016-04-28 04:34:21

标签: swift iphone

下面是代码,如果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)
 }

2 个答案:

答案 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
}