一尘不染

当UITextField满或为空时显示警报

swift

以下是其中的代码,如果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)
 }

阅读 290

收藏
2020-07-07

共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
}
2020-07-07