验证单个文本字段中的密码 Swift

Validating Password in Single Text Field Swift

这是我的应用程序的主要故事板:

我有一个 iOS 应用程序,我必须在输入 4 位数字后将标签内的文本从 "Set Passcode" 更改为 "Confirm Passcode",然后清除文本字段。密码输入是通过点击按钮完成的。

现在,我必须再次给出 4 位数字并使用用户默认值比较两个条目。我知道如何使用两个文本字段来实现这一点,但不知道如何使用单个文本字段来实现它。

创建一个 Label、TextField 和一个 Button,将它们全部添加到您的视图控制器并为 Button 创建一个 IBAction。在Attribute Inspector中设置按钮的tag number为2,也可以将TextFields Keyboard type改为Number Pad。

Setup

现在添加三个变量:

var Password1: String?
var Password2: String?
var Offical_Password: String?

在 ViewDidLoad 函数中将按钮标签设置为 1:

Button.tag = 1

下面显示的这两个函数将处理 TextField 和 Label 的设置。它还会检查 Password1 是否等于 Password2,然后设置 Official_Password:

    func Password () {
    if (TextField.text == "") {
        // Password is required
    } else {
        Lable.text = "Confirm Password"
        Password1 = TextField.text
        TextField.text = ""
    }
}


func Password_Confimed () {
    if TextField.text == "" {
        // Confirmation Password is required
    } else {
        Password2 = TextField.text
    }
    if Password1 == Password2 {
        Lable.text = "Done"
        Offical_Password = Password1
        TextField.text = ""
    } else {
        // Handle error
    }
}

最后在IBAction函数中添加:

@IBAction func Button_Pressed(sender: AnyObject) {
    if Button.tag == 1 {
        Password()
        Button.tag = 2
    } else if Button.tag == 2 {
        Password_Confimed()
        // Go to another View Controller
    }
}

The Final Result

您必须添加您希望如何处理问题,例如确保密码不太弱以及设置密码后您实际想做什么。