输入身份证号要自定义键盘?太low了吧!
小朋友你是不是傻(•̅ ȷ̫ •̅)
良辰我奉劝你不要酱做(除非UI 要求)
构建思路
- 选择合适的键盘
- 输入时进行调整
- 结束编辑再次调整
核心规避风险
具体做法
贴代码演示
class:superclass<UIUITextFieldDelegate>
self.IDCardNoField.text = [[UITextField alloc]init];
self.IDCardNoField.delegate = self;
- 键盘设置建议使用的键盘
UIKeyboardTypeDecimalPad
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:@""];
}
}
当然,如果你需要在使用或者提交表单时判断身份证是否合法可以看[下一篇]
© 著作权作者:卢金龙
网友评论