是否有一种聪明的方法让用户在ios / iphone UITextField中切换隐藏和查看密码,用户可以在其中输入密码,并可以选择隐藏或查看密码。 提前谢谢。
答案 0 :(得分:22)
只需设置
.secureTextEntry = YES
无法工作我认为由于一个错误(或一个功能),如果textField有焦点。
如果textField当前是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
}
答案 1 :(得分:7)
- (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;
}
}
答案 2 :(得分:3)
马里奥的回答很好,帮了我很多。
但是如果您在文本字段中使用自定义字体,一旦从安全条目更改为纯文本,文本字段的文本将使用错误(非自定义)字体绘制,直到用户输入另一个字符
通过一点点破解,我能够通过模拟代码中的字符输入来解决这个问题。
此修改后的Mario代码适用于具有自定义字体的字段:
- (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];
}
}
答案 3 :(得分:2)
您可以使用secureTextEntry
的{{1}}属性。当你想隐藏(为每个角色显示点)时,你可以使用UITextField
如果您想显示密码,请使用yourTextField.secureTextEntry=YES;