1.项目中经常遇到密码需要明文,密文切换的样式,如下图:
2.切换过程中,会在10以下的系统会出现几个问题,1.出现空格,光标位置错乱,2.字体变化,3.密文时输入文字清空,下面分别列举出解决办法:
3.1 第一种问题解决办法,先保存文本,再清空输入,再赋值,就解决了空格问题
- (void)eyesBtnClick:(UIButton *)btn
{
self.textField.secureTextEntry = btn.selected;
btn.selected = !btn.selected;
NSString *oriText = self.textField.text;
self.textField.text = @"";
self.textField.text = oriText;
}
3.2 字体变化问题,重新设置一下字体,保持和现在设置的一样
- (void)eyesBtnClick:(UIButton *)btn
{
self.textField.secureTextEntry = btn.selected;
btn.selected = !btn.selected;
NSString *oriText = self.textField.text;
self.textField.text = @"";
self.textField.text = oriText;
self.textField.font = [UIFont fontWithName:@"HelveticaNeue" size:16];
}
3.3 密文输入清空问题,在代理里面,加多一个判断能避免密文清空的问题,如下:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//明文切换密文后避免被清空
NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (textField == self.textField && textField.isSecureTextEntry) {
textField.text = toBeString;
return NO;
}
return YES;
}