验证iOS

时间:2016-10-03 00:53:51

标签: ios swift uitextfield

我正在尝试验证我的凭据(用户名和密码)。由于某种原因,即使我将用户名和密码字段留空并单击“登录”按钮,代码也永远不会进入第一个if循环。 附加代码和屏幕截图。 有人可以帮我解决这个问题吗?

import UIKit

class FirstViewController: UIViewController {
    @IBOutlet weak var NameField: UITextField!
    @IBOutlet weak var PasswordField: UITextField!

    @IBAction func textFieldDoneEditing(sender: UITextField){
        sender.resignFirstResponder()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
       // let stringkey = NSUserDefaults.standardUserDefaults()
       // NameField.text = stringkey.stringForKey("savedusername")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func LogIn(sender: AnyObject) {
        //let myText  = NameField.text;
        //NSUserDefaults.standardUserDefaults().setObject(myText, forKey: "savedusername")
        //NSUserDefaults.standardUserDefaults().synchronize()
        if(NameField == "" || PasswordField == "")
        {
            let alert = UIAlertController(title: nil , message: "Invalid Credentials!", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }

        if(NameField != ""  && PasswordField != ""){
            let alert = UIAlertController(title: nil , message: "Login Successfull", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
}

enter image description here

3 个答案:

答案 0 :(得分:1)

您将UITextField与“{而非text属性进行比较。

请尝试使用NameField.text等。

答案 1 :(得分:0)

您已尝试将NSString @IBAction func LogIn(sender: AnyObject) { if(NameField.text == "" || PasswordField.text == "") { //Please Enter valid credential... } if(NameField.text != "" && PasswordField.text != ""){ //Login successfully... } } 进行比较,因此您的代码将永远不会根据您的条件执行。

尝试使用以下代码

Get-Counter -Computername RKCDR1 -Counter '\Process(*)\% Processor Time' |
    Select -ExpandProperty countersamples |
    Select-Object -Property instancename, cookedvalue |
    Sort-Object -Property cookedvalue -Descending |
    Select-Object -First 10 |
    ft -AutoSize

答案 2 :(得分:0)

在swift下面的代码中我们可以检查textfield是否为空。

if textfield.text?.characters.count == 0 {
    print("Empty")
}else {
    print("Not Empty")
}