iOS UITextField 明文密文切换时密文被清空问题

使用UITextField从明文切换到密文后,输入任何值都会将密文的输入先清空。这个是UITextField默认的设置,好像也没有一个属性值可以直接控制吧。不过在代理里面,加多一个判断也能避免密文清空的问题

第一种方案:通过定制UITextField的代理方法解决

关键代码

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 明文切换密文后避免被清空
    // 是密码框 并且 是密文状态
    if (textField == self.tf && textField.isSecureTextEntry) {
        NSString *secureString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        textField.text = secureString;
        // 返回NO表示 舍弃 通过这个代理方法 改变 UITextField的文本内容
        return NO;
    }
    return YES;
}

第二种方案:通过在同一个位置放置两个UITextField来解决(这个方法比较取巧)

关键代码

- (void)makeSecure:(BOOL)secure {
    if (secure) {
        CGRect rect = self.tf.frame;
        NSString *ph = self.tf.placeholder;
        NSString *text = self.tf.text;
        [self.tf removeFromSuperview];
        self.tf = nil;
        // 这里调用的gen...的方法是用来封装生成相同的UITextField
        [self genTFWithFrame:rect placeHodler:ph secureTextEntry:secure];
        self.tf.text = text;
        [self.tf becomeFirstResponder];
    }
    else {
        self.tf.secureTextEntry = secure;
    }
}

- (void)genTFWithFrame:(CGRect)rect placeHodler:(NSString *)placeHolder secureTextEntry:(BOOL)secureTextEntry {
    UITextField *tf = nil;
    if (secureTextEntry) {
        tf = [[CustomSecureTextField alloc] initWithFrame:rect];
    }
    else {
        tf = [[UITextField alloc] initWithFrame:rect];
    }
    [self.bgView addSubview:tf];
    tf.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeHolder attributes:@{NSForegroundColorAttributeName:kColorWithHex(0x999999)}];
    tf.secureTextEntry = secureTextEntry;
    _tf = tf;
    tf.delegate = self;
}


@interface CustomSecureTextField : UITextField

@end

@implementation CustomSecureTextField

- (BOOL)becomeFirstResponder {
    if (self.isFirstResponder) {
        return YES;
    }
    [super becomeFirstResponder];
    if (!self.isSecureTextEntry) {
        return YES;
    }
    
    [self insertText:self.text];

    return YES;
}

@end

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值