-(NSString *)formatterBankCardNum:(NSString *)string
{
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;
}
----------------------------------textfield代理实现每隔四位添加空格-------------------------------------
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *text = [textField text];
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
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.length >= 24)
{
[_textFieldBankCardNumber resignFirstResponder];
return NO;
}
[textField setText:newString];
_textFieldBankCardNumber.text=textField.text;
return NO;
}