Reputation: 1678
Is there a clever way to let the user switch between hide and view password in an ios/iphone UITextField where the user can enter a password and would have the option of either hide it or view it. thanks in advance.
Upvotes: 11
Views: 21881
Reputation: 531
- (IBAction)ShowPass:(UIButton *)sender {
if (self.password.secureTextEntry == YES) {
[self.showPass setTitle:@"HIDE" forState:(UIControlStateNormal)];
self.password.secureTextEntry = NO;
}else{
[self.showPass setTitle:@"SHOW" forState:(UIControlStateNormal)];
self.password.secureTextEntry = YES;
}
}
Upvotes: 7
Reputation: 4520
Simply setting
.secureTextEntry = YES
wont work I think due to a bug (or a feature), if the textField has focus.
Use something like this to make it work also if the textField is currently firstResponder
-(void) toggleTextFieldSecureEntry: (UITextField*) textField {
BOOL isFirstResponder = textField.isFirstResponder; //store whether textfield is firstResponder
if (isFirstResponder) [textField resignFirstResponder]; //resign first responder if needed, so that setting the attribute to YES works
textField.secureTextEntry = !textField.secureTextEntry; //change the secureText attribute to opposite
if (isFirstResponder) [self.textField becomeFirstResponder]; //give the field focus again, if it was first responder initially
}
Upvotes: 24
Reputation: 7704
Mario's answer works fine and helped me a lot.
But if you use custom font in a text field, once you change from secure entry to plain text, the text field's text will be drawn with wrong (not custom) font until user inputs another character.
With a little hack I was able to fix this issue by simulating that character input from code.
This modified Mario's code should work for fields with custom fonts:
- (void)toggleTextFieldSecureEntry:(UITextField *)textField {
BOOL isFirstResponder = textField.isFirstResponder;
if (isFirstResponder) {
[textField resignFirstResponder];
}
textField.secureTextEntry = !textField.secureTextEntry;
if (isFirstResponder) {
[textField becomeFirstResponder];
}
// When using custom font and changing from secure entry to plain text, the text is initially drawn with wrong font
// until a next character is input by user. This hack fixes the font immediatelly (simulate add and delete character)
if (!textField.isSecureTextEntry) {
[textField insertText:@"x"];
[textField deleteBackward];
}
}
Upvotes: 3
Reputation: 8771
For Swift, only the assignment values change from YES/NO to true/false boolean values.
password.secureTextEntry = true //Visible
password.secureTextEntry = false //InVisible
Upvotes: 1
Reputation: 1294
You can use secureTextEntry
property of UITextField
. When you want to hide (show dot for each character) you can use yourTextField.secureTextEntry=YES;
And when you want to show password use yourTextField.secureTextEntry=NO;
Upvotes: 2