Paul Peelen Paul Peelen - 1 year ago 313
Swift Question

UITextField secureTextEntry toggle set incorrect font

I have an

which I use as a password field. It has by default
set to
I also have a
to toggle the show/hide of the password.

When I change the textfield from
set to
, the font gets weird. Seems it becomes Times New Roman or similar.

I have tried re-setting the font to system with size 14, but it didn't change anything.

Example of what happens (with initial
set to

My code:

@IBAction func showHidePwd(sender: AnyObject) {
textfieldPassword.secureTextEntry = !textfieldPassword.secureTextEntry

// Workaround for dot+whitespace problem
if !textfieldPassword.secureTextEntry {
let tempString = textfieldPassword.text
textfieldPassword.text = nil
textfieldPassword.text = tempString
textfieldPassword.font = UIFont.systemFontOfSize(14)

if textfieldPassword.secureTextEntry {
showHideButton.setImage(UIImage(named: "EyeClosed"), forState: .Normal)
} else {
showHideButton.setImage(UIImage(named: "EyeOpen"), forState: .Normal)


Answer Source

In fact to solve the problem I used a mix of the two previous responses.

In my particular case, my view contains only two fields. So I :

  • Memorize the field who has the focus (if any).
  • If the field switch to "not secure", I set the font to nil, set the font back to its original value, and resignFirstResponder on text field.
  • If the field switch "to secure", I just resignFirstResponder on the text field.
  • In all cases, I restore the focus to the original field (if any).

With this method, I have not problem of show/hide keyboard, it works perfectly.

Regards. S├ębastien.

BOOL loginTextFieldHadFocus = self.loginTextField.isFirstResponder;
BOOL passwordTextFieldHadFocus = self.passwordTextField.isFirstResponder;
if (self.passwordTextField.isSecureTextEntry)
    self.passwordTextField.secureTextEntry = NO;
    self.passwordTextField.font = nil;
    self.passwordTextField.font = [UIFont systemFontOfSize:19.0 weight:UIFontWeightRegular];
    [self.passwordTextField resignFirstResponder];
    self.passwordTextField.secureTextEntry = YES;
    [self.passwordTextField resignFirstResponder];
if (loginTextFieldHadFocus)
    [self.loginTextField becomeFirstResponder];
else if (passwordTextFieldHadFocus)
    [self.passwordTextField becomeFirstResponder];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download