欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-02-18 13:13:58
今天做格式化银行卡,避免重复造*,找度娘查了下,看到一个不错的实现方式,记录下来,并附带实现思路 #pragma mark - uitextfielddeleg...

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

#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;
}