Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField has trailing the whitespace after secureTextEntry toggle

I am trying to toggle the password text field, but I am facing a problem of white space at right side of text field.

//Eye button action.

@IBAction func btnEyePassword(sender: AnyObject)
{
    //If password text is secure.
    if (self.passrordText.secureTextEntry == true)
    {           
        self.passrordText.secureTextEntry = false         
    }

    else
    {
       self.passrordText.secureTextEntry = true          
    }
}
like image 355
Kishor Pahalwani Avatar asked Jul 22 '16 11:07

Kishor Pahalwani


1 Answers

Swift 4 solution

func togglePasswordVisibility() {
        password.isSecureTextEntry = !password.isSecureTextEntry
        if let textRange = password.textRange(from: password.beginningOfDocument, to: password.endOfDocument) {
            password.replace(textRange, withText: password.text!)
        }
    }

You don't need extra if statement for simple toggle isSecureTextEntry property, but you should replace text this way to force UITextField recalculate text width to avoid extra space.

UPDATE

Swift 4.2

Instead of

password.isSecureTextEntry = !password.isSecureTextEntry

you can do this

password.isSecureTextEntry.toggle()
like image 91
Eugene Chybisov Avatar answered Nov 02 '22 23:11

Eugene Chybisov