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

猜你喜欢

转载自blog.csdn.net/allanGold/article/details/114162068