//检测是否为纯数字
- (BOOL)isPureInt:(NSString *)string{
NSScanner* scan = [NSScanner scannerWithString:string];
int val;
return [scan scanInt:&val] && [scan isAtEnd];
}
//在UITextField的代理方法中
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
//检测是否为纯数字
if ([self isPureInt:string]) {
//添加空格,每4位之后,4组之后不加空格,格式为xxxx xxxx xxxx xxxx xxxxxxxxxxxxxx
if (textField.text.length % 5 == 4 && textField.text.length < 22) {
textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
}
//只要30位数字
if ([toBeString length] >= 19+4+11)
{
toBeString = [toBeString substringToIndex:19+4+11];
textField.text = toBeString;
[textField resignFirstResponder];
return NO;
}
}
else if ([string isEqualToString:@""]) { // 删除字符
if ((textField.text.length - 2) % 5 == 4 && textField.text.length < 22) {
textField.text = [textField.text substringToIndex:textField.text.length - 1];
}
return YES;
}
else{
return NO;
}
return YES;
}
网友评论