Dummy Code
Dummy Code

Reputation: 1898

Stop UITextField Secure Text From Clearing Existing Text

I have a UITextField that is a password field declared by using

passwordField.secureTextEntry = YES;

My issue is that when I type half my password, click on a different component, and come back to the passwordField and start typing again, iOS clears the existing text.

Is there a way to prevent this from happening or turn it off?

-Henry

Upvotes: 1

Views: 5397

Answers (3)

Hammad Lodhi
Hammad Lodhi

Reputation: 1

Well I have the same situation when I was changing keyboard type to make my password combo of 4(digits)+1(alpha), to stop clearing secureTextEntry,

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
textField.keyboardType = UIKeyboardTypePhonePad;
[textField reloadInputViews];

return YES;
}

It reloads UITextField but not its text, so without clearing text it changed the keyboard from alpha to numeric vice versa. You can use it for your own functionality.

Upvotes: 0

Daniel
Daniel

Reputation: 61

Simplest way to do this is to implement delegate for UITextField with a code similar to this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)replacementString {
  if (textField.text) {
      textField.text = [textField.text stringByReplacingCharactersInRange:range withString:replacementString];
  } else {
      textField.text = replacementString;
  }

  return NO;
}

Upvotes: 4

Wain
Wain

Reputation: 119031

By default, no, you can't do it for secure text fields. You can work around it though.

Implement the delegate method textField:shouldChangeCharactersInRange:replacementString: and use the values passed to decide what to do.

i.e. if the range is the entire string and the replacement is an empty string, don't allow the change. The new text might be provided as the newly typed character, you'll need to check what parameters the method actually receives.

Upvotes: 3

Related Questions