2016-04-28 48 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

它們被定義爲 –

相關問題