sk123
sk123

Reputation: 600

Show password typed by user in UITextfield in Swift

I have password UITextfield that is currently turned on as secure entry. I would like to show the user the password he has typed inform of text again in the UITextfield when the UISwitch is turned on. Here is my implementation that so far. It works when i print it out in the console but doesn't in the UITextfield. I would like to show it on once the UISwitch is turned on and off when the UISwitch is turned off.

@IBOutlet weak var existingPasswordTexfField: UITextField!
@IBOutlet weak var newPasswordTextField: UITextField!
@IBOutlet weak var changePasswordSwitch: UISwitch!

@IBAction func showPassword(_ sender: UISwitch) {
    if changePasswordSwitch.isOn {
        guard let oldText = existingPasswordTexfField.text else { return }

        if existingPasswordTexfField.isSecureTextEntry {
            existingPasswordTexfField.text = oldText
        } else {
            print("Pawword is already secure")
        }
    }
}

Upvotes: 2

Views: 4345

Answers (3)

AnderCover
AnderCover

Reputation: 2661

According to Apple Doc isSecureTextEntry is a writable property

So in your showPassword IBAction you need to toggle it at some point :

existingPasswordTexfField.isSecureTextEntry = false

or just

existingPasswordTexfField.isSecureTextEntry = !changePasswordSwitch.isOn

Upvotes: 4

sk123
sk123

Reputation: 600

This is also works

existingPasswordTexfField.isSecureTextEntry = changePasswordSwitch.isOn ? false : true

Upvotes: 1

Kyle H
Kyle H

Reputation: 921

You'll need to change the isSecureTextEntry flag on the textfield when the user flips the switch.

@IBAction func showPassword(_ sender: UISwitch) {
    existingPasswordTextField.isSecureTextEntry = changePasswordSwitch.isOn
}

Upvotes: 3

Related Questions