2016-04-28 46 views
0

以下代码表示如果userNameTF或passwordTF已满或为空,它将显示警报。当UITextField已满或为空时显示警报Swift

@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

当检查可选布尔你需要处理一个第三可能的结果是零所以加一个很好的例子==真,假== ==或零 –

+0

看看这个答案以及http://stackoverflow.com/questions/29381994/swift-check-string-for-nil-empty – user3353890

+0

嗨@Roberto C Dl Garza:请检查我的答案并接受它。 –

回答

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 
} 
+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. 
    } 

享受编码...它的工作很好。

+0

它们被定义为 –

相关问题