iOS 导航合集iOS开发

iOS UITextField输入身份证号设置

2017-05-09  本文已影响1383人  Apple_JinlongLu

简书

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

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

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

构建思路

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

核心规避风险

具体做法

贴代码演示
class:superclass<UIUITextFieldDelegate>

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

self.IDCardNoField.delegate = self;

iOS UITextField输入身份证号设置
    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 校验身份证号码是否正确

上一篇下一篇

猜你喜欢

热点阅读