公司项目需求根据用户输入的卡号自动识别是哪家银行,一般都是根据卡号的前六位进行判断,因此在网上找了个demo进行了一些改动,下面是实现的具体代码。
[原文链接] http://www.jianshu.com/p/47ba8bd5aee3
#pragma mark --UITextFieldDelegate
//输入时一直监听,返回YES表示修改生效,返回NO表示不修改
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string {
if(textField.tag== 1) {
return YES;
}
NSString*text = [self.cardNumTextFieldtext];
//返回一个字符集,指定字符串中包含的字符
NSCharacterSet*characterSet = [NSCharacterSetcharacterSetWithCharactersInString:@"0123456789\b"];
//string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
//invertedSet除了characterSet中包含的字符都找出来
if([stringrangeOfCharacterFromSet:[characterSetinvertedSet]].location != NSNotFound) {
return NO;
}
text = [text stringByReplacingCharactersInRange:rangewithString:string];
text = [text stringByReplacingOccurrencesOfString:@" "withString:@""];
//不能写nil,nil是空指针,但@“”不是空指针,nil会造成无法添加字符串
NSString*newString = @"";
while(text.length > 0) {
//每4位截取/不够4位有多少截取多少
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 >= 24) {
return NO;
}
[self.cardNumTextField setText:newString];
NSString*originalStr = [newString stringByReplacingOccurrencesOfString:@" "withString:@""];
//判断实哪家银行,并赋值
if([self returnBankName:originalStr].length > 0) {
self.bankName.text= [self returnBankName:originalStr];
}
//小于6位清空
if(self.cardNumTextField.text.length < 6) {
self.bankName.text = @"";
}
return NO;
}
//编辑结束
- (void)textFieldDidEndEditing:(UITextField*)textField {
if(self.cardNumTextField.text.length<= 0 ||self.cardNumTextField.text.length> 24) {
//提示错误信息
self.bankName.text = @"";
}
}
//根据卡号判断银行
- (NSString*)returnBankName:(NSString*)cardName {
NSString*filePath = [[NSBundle mainBundle]pathForResource:@"bank"ofType:@"plist"];
NSDictionary*resultDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
NSArray*bankBin = resultDic.allKeys;
if(cardName.length< 6) {
return@"";
}
NSString*cardbin_6 ;
if(cardName.length>= 6) {
cardbin_6 = [cardName substringWithRange:NSMakeRange(0, 6)];
}
NSString*cardbin_8 =nil;
if(cardName.length>= 8) {
//8位
cardbin_8 = [cardName substringWithRange:NSMakeRange(0, 8)];
}
if([bankBin containsObject:cardbin_6]) {
return [resultDic objectForKey:cardbin_6];
} else if ([bankBin containsObject:cardbin_8]){
return [resultDic objectForKey:cardbin_8];
} else {
return @"";
}
return@"";
}
下面是效果图
github地址