验证iOS

时间:2016-08-09 13:17:18

标签: ios swift validation

我正在为iOS应用设置密码屏幕。我使用单个文本字段设置密码并确认密码。我在设置两个值的标志时遇到困难并验证它们。

func handleInput(str: String)
{
    if txtField.text?.characters.count == 4
    {
        print("Set Passcode: \(txtField.text!)")

        let myValue:NSString = txtField.text!
        NSUserDefaults.standardUserDefaults().setObject(myValue, forKey:"Username1")
        NSUserDefaults.standardUserDefaults().synchronize()
        print(" Value1 \(myValue)")

        resignFirstResponder()
        label.text? = "Confirm Passcode"
        txtField.text = ""

2 个答案:

答案 0 :(得分:0)

您可以使用从xib / storyboard

更改的事件编辑

Editing Changed

然后你可以检查发件人的文本,这样你就可以对UITextView s

使用相同的功能

修改

检查文本的动作的简要示例:

@IBAction func textFieldDidChange(sender: UITextView) {
    if sender == passwordTextView {
        // check passwordTextView.text
    } else if sender == passwordConfirmTextView {
        // check passwordConfirmTextView.text
    }
}

答案 1 :(得分:0)

请勿忘记导入UITextFieldDelegate,如下面的代码所示。你可以这样做:

class File2: UIViewController, UITextFieldDelegate{

@IBOutlet weak var textField: UITextField!
@IBOutlet weak var label: UILabel!
var i = 0
var password = ""
var confirmPassword = ""

override func viewDidLoad() {
    super.viewDidLoad()
    textField.delegate = self
    textField.secureTextEntry = true
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let newLength = count(textField.text.utf16) + count(string.utf16) - range.length
    if newLength == 4{
        if i == 0{
            password = textField.text!
            textField.text = ""
            textField.placeholder = "Confirm Password"
            i+=1
        }
        else if i == 1{
            confirmPassword = textField.text!
            textField.text = ""
            i = 0
            if confirmPassword == password{
                // save the password... (Your Code)
                // I know userdefaults is not a good way to store passwords, but for tutorial purposes, it's OK.
                NSUserDefaults.standardUserDefaults.setValue(password, forKey: "password")
                print("Account Succesfully Created With Password: \(password)!")
            }
        }
    }
    return newLength <= 4
    return true
}

}

读取密码:

查看 Stack Overflow UserDefaults文档。