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
}
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With