今天做格式化银行卡,避免重复造轮子,找度娘查了下,看到一个不错的实现方式,记录下来,并附带实现思路
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
#pragma mark - UITextFieldDelegate UITextField键入字符后调用 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { //拿到为改变前的字符串 NSString *text = [textField text]; //键入字符集,\b标示删除键 NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@ "0123456789\b" ]; //对当前键入字符进行空格过滤 string = [string stringByReplacingOccurrencesOfString:@ " " withString:@ "" ]; //invertedSet会对当前结果集取反,检查当前键入字符是否在字符集合中,如果不在则直接返回NO 不改变textField值 if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) { return NO; } //增加当前键入字符在改变前的字符串尾部 text = [text stringByReplacingCharactersInRange:range withString:string]; //再次确认去掉字符串中空格 text = [text stringByReplacingOccurrencesOfString:@ " " withString:@ "" ]; //初始化字符用来保存格式化后的字符串 NSString *newString = @ "" ; //while中对text进行格式化 while (text.length > 0 ) { //按4位字符进行截取,如果当前字符不足4位则按照当前字符串的最大长度截取 NSString *subString = [text substringToIndex:MIN(text.length, 4 )]; //将截取后的字符放入需要格式化的字符串中 newString = [newString stringByAppendingString:subString]; if (subString.length == 4 ) { //截取的字符串长度满4位则在后面增加一个空格符 newString = [newString stringByAppendingString:@ " " ]; } //将text中截取掉字符串去掉 text = [text substringFromIndex:MIN(text.length, 4 )]; } //再次确认过滤掉除指定字符以外的字符 newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]]; //国内银行卡一般为16~19位 格式化后增加4个空格 也就是最多23个字符 if (newString.length > 23 ) { return NO; } //手动对textField赋值 [textField setText:newString]; //返回NO 则不通过委托自动往当前字符后面增加字符,达到格式化效果 return NO; } |
原文链接:http://blog.csdn.net/leiyu231/article/details/53619954