项目中要实现:
以下是总结的代码
1.输入
#pragma mark - UITextFieldDelegate
// 银行卡输入每4位分隔
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == _cardNumberTF) {
// 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 >= 20) {
return NO;
}
[textField setText:newString];
return NO;
}
return YES;
}
2.显示
// 给定字符串根据指定的个数进行分组,每一组用空格分隔
- (NSString *)groupedString:(NSString *)string {
NSString *str = [string stringByReplacingOccurrencesOfString:@" " withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, string.length)];
// 根据长度计算分组的个数
NSInteger groupCount = (NSInteger)ceilf((CGFloat)str.length /4);
NSMutableArray *components = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < groupCount; i++) {
if (i*4 + 4 > str.length) {
[components addObject:[str substringFromIndex:i*4]];
} else {
NSString * secureStr = [str substringWithRange:NSMakeRange(i*4, 4)];
secureStr = [secureStr stringByReplacingCharactersInRange:NSMakeRange(0, 4) withString:@"****"];
[components addObject:secureStr];
}
}
NSString *groupedString = [components componentsJoinedByString:@" "];
return groupedString;
}
网友评论