公司項(xiàng)目需求根據(jù)用戶輸入的卡號(hào)自動(dòng)識(shí)別是哪家銀行没讲,一般都是根據(jù)卡號(hào)的前六位進(jìn)行判斷应役,因此在網(wǎng)上找了個(gè)demo進(jìn)行了一些改動(dòng)罗标,下面是實(shí)現(xiàn)的具體代碼显沈。
[原文鏈接] http://www.reibang.com/p/47ba8bd5aee3
#pragma mark --UITextFieldDelegate
//輸入時(shí)一直監(jiān)聽,返回YES表示修改生效,返回NO表示不修改
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string {
if(textField.tag== 1) {
return YES;
}
NSString*text = [self.cardNumTextFieldtext];
//返回一個(gè)字符集,指定字符串中包含的字符
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會(huì)造成無法添加字符串
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:@""];
//判斷實(shí)哪家銀行,并賦值
if([self returnBankName:originalStr].length > 0) {
self.bankName.text= [self returnBankName:originalStr];
}
//小于6位清空
if(self.cardNumTextField.text.length < 6) {
self.bankName.text = @"";
}
return NO;
}
//編輯結(jié)束
- (void)textFieldDidEndEditing:(UITextField*)textField {
if(self.cardNumTextField.text.length<= 0 ||self.cardNumTextField.text.length> 24) {
//提示錯(cuò)誤信息
self.bankName.text = @"";
}
}
//根據(jù)卡號(hào)判斷銀行
- (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地址