标签:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *text = [textField text]; NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"]; string = [string stringByReplacingOccurrencesOfString:@" " withString:@""]; if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) { return NO; } text = [text stringByReplacingCharactersInRange:range withString:string]; text = [text stringByReplacingOccurrencesOfString:@" " withString:@""]; NSString *newString = @""; while (text.length > 0) { NSString *subString = [text substringToIndex:MIN(text.length, 4)]; newString = [newString stringByAppendingString:subString]; if (subString.length == 4) { newString = [newString stringByAppendingString:@" "]; } text = [text substringFromIndex:MIN(text.length, 4)]; } newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]]; if (newString.length >= 20) { return NO; } [textField setText:newString]; return NO; }
// 16位以内 (3个空格) NSString *str_bangNum = [NSString stringWithFormat:@"%@%@",textField.text,string]; if (textField.text.length < 23) { //银行卡只能输入数字 cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet]; NSString *filterStr = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; BOOL basicTest = [string isEqualToString:filterStr]; if(!basicTest) { return NO; } //显示内容的格式化 if(range.length > 0 && str_bangNum.length > 0)// 支持删除 { NSString *tmp_str = [str_bangNum bankNumToNormalNum]; str_bangNum = [tmp_str substringToIndex:(tmp_str.length - 1)]; } str_bangNum = [str_bangNum normalNumToBankNum]; textField.text = str_bangNum; return NO; } else { if(range.length > 0 && str_bangNum.length > 0)// 支持删除 { NSString *tmp_str = [str_bangNum bankNumToNormalNum]; str_bangNum = [tmp_str substringToIndex:(tmp_str.length - 1)]; str_bangNum = [str_bangNum normalNumToBankNum]; textField.text = str_bangNum; } return NO; }
// 正常号转银行卡号 - 增加4位间的空格 -(NSString *)normalNumToBankNum { NSString *tmpStr = [self bankNumToNormalNum]; int size = (tmpStr.length / 4); NSMutableArray *tmpStrArr = [[NSMutableArray alloc] init]; for (int n = 0;n < size; n++) { [tmpStrArr addObject:[tmpStr substringWithRange:NSMakeRange(n*4, 4)]]; } [tmpStrArr addObject:[tmpStr substringWithRange:NSMakeRange(size*4, (tmpStr.length % 4))]]; tmpStr = [tmpStrArr componentsJoinedByString:@" "]; return tmpStr; } // 银行卡号转正常号 - 去除4位间的空格 -(NSString *)bankNumToNormalNum { return [self stringByReplacingOccurrencesOfString:@" " withString:@""]; }
http://blog.csdn.net/h3c4lenovo/article/details/8515304
标签:
原文地址:http://www.cnblogs.com/why-not/p/4782367.html