Search code examples
iosswiftuitextfield

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")
        }
    }
}

Solution

  • 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