iOS UITextField输入身份证号设置

输入身份证号要自定义键盘?太low了吧!

小朋友你是不是傻(•̅ ȷ̫ •̅)

良辰我奉劝你不要酱做(除非UI 要求)

构建思路

  1. 选择合适的键盘
  2. 输入时进行调整
  3. 结束编辑再次调整

核心规避风险

具体做法

贴代码演示
class:superclass

self.IDCardNoField.text = [[UITextField alloc]init];

self.IDCardNoField.delegate = self;

  • 键盘设置建议使用的键盘UIKeyboardTypeDecimalPad
iOS UITextField输入身份证号设置_第1张图片
    self.IDCardNoField.placeholder = @"最后一位有X用 . 代替";
    self.IDCardNoField.keyboardType = UIKeyboardTypeDecimalPad;
代理中应做的:
  • 输入时
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSLog(@"%@",string);
    
    if ([string isEqualToString:@" "]) {
        return NO;
    }
    if(self.IDCardNoField == textField){
        if ([string isEqualToString:@"."]&&newLength == 18) {
            textField.text = [NSString stringWithFormat:@"%@X",textField.text];
            return NO;
        }if ([string isEqualToString:@"."]) {
            return NO;
        }
        
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789X."] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        return [string isEqualToString:filtered]&&newLength <= 18? YES :NO   ;
    }
    return newLength <= 16;
    
}
  • 结束编辑再次调整
- (void)textFieldDidEndEditing:(UITextField *)textField;{
    if (self.IDCardNoField== textField) {
        NSCharacterSet *setToRemove = [[ NSCharacterSet characterSetWithCharactersInString:@"0123456789X."]
                                       invertedSet ];
        textField.text  = [[textField.text  componentsSeparatedByCharactersInSet:setToRemove] componentsJoinedByString:@""];
    }
}

当然,如果你需要在使用或者提交表单时判断身份证是否合法可以看[下一篇]


[上一篇]:iOS UI状态保存和恢复
[下一篇]:iOS 校验身份证号码是否正确






我的专题:

iOS开发

Mac汉化(游戏/软件)

你可能感兴趣的:(iOS UITextField输入身份证号设置)