Search code examples
swiftuikitpasswordsuitextfield

How to hide the last digit while writing a password in swift


Recently I've been working on a UITextField that hides the password while editing text on the loginPage, password field.

As everyone knows .isSecureTextEntry = true solves the problem up to a point. However, while typing the password, the last character appears and is perceived as a security hole in a way. So I could not find out a solution how to solve this. Thank you in advance for your answers.

I attached two pictures.

The solution offered by UIKIT today.

textField.isSecureTextEntry = true

It's what I wanted.

I want this


Solution

  • When ever you input the character the func textField(_:shouldChangeCharactersIn:replacementString:) will call to replace old text with new text. So you just need to catch the value and don't let it update by default.

    textField.isSecureTextEntry = true
    textField.delegate = self // add delegate to catch the action
    

    Get the value when changing in your TextField and don't get it update the UI automatically.

    extension ViewController : UITextFieldDelegate {
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if let currentText = self.textField.text as? NSString {
                let newText = currentText.replacingCharacters(in: range, with: string) // change to new one
                self.textField.text = newText // assign it back to textField text
                return false // don't let it update automically
            }
            
            return true // by default
        }
    }
    

    If you have multiple textField in the screen you must checked if the current changing is your password one before. If yes return false else return true like default.