iOS 输入银行卡号每4位一起展示
2019-07-12 本文已影响0人
魔力双鱼
1.输入银行卡号
UITableView 有一个cell需要输入银行卡号,每输入4位后面加一个空格
//银行卡每4位展示
- (BOOL)textField:(ML_BaseTextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField.indexPath.section == 1 && textField.indexPath.row == 2) {
// 4位分隔银行卡卡号
NSString *text = [textField text];
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
return NO;
}
text = [text stringByReplacingCharactersInRange:range withString:string];
text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString *newString = @"";
while (text.length > 0) {
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 stringByReplacingOccurrencesOfString:@" " withString:@""].length >= 21) {
return NO;
}
[textField setText:newString];
return NO;
}
return YES;
}
2.显示银行卡号
没有空格的银行卡号,没4位间隔的显示出来
//银行卡每四位显示
- (NSString *)formatterBankCardNum:(NSString *)string{
if (![string notNilOrEmpty]) {
return nil;
}
NSString *tempStr=string;
NSInteger size =(tempStr.length / 4);
NSMutableArray *tmpStrArr = [[NSMutableArray alloc] init];
for (int n = 0;n < size; n++){
[tmpStrArr addObject:[tempStr substringWithRange:NSMakeRange(n*4, 4)]];
}
[tmpStrArr addObject:[tempStr substringWithRange:NSMakeRange(size*4, (tempStr.length % 4))]];
tempStr = [tmpStrArr componentsJoinedByString:@" "];
return tempStr;
}