iOS 中 使用UITextField格式化银行卡号码的解决方案

2025-05-29 0 92

今天做格式化银行卡,避免重复造轮子,找度娘查了下,看到一个不错的实现方式,记录下来,并附带实现思路

?

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;

}

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 iOS 中 使用UITextField格式化银行卡号码的解决方案 https://www.kuaiidc.com/91935.html

相关文章

发表评论
暂无评论