最近项目要做一个绑定银行卡的功能,于是我打开微信和支付宝瞄了一眼,对比后发现微信和支付宝在卡号输入的一些细节上处理是不一样的,举个例子:输入卡号的时候,我发现中间有一位数输错了,然后试着去修改,微信的处理是删除完这个数字,光标直接移动到末尾。。这不科学啊,我还没有修改完呢。。而支付宝的处理就比较合理了,删除完后光标还在那个位置,可以继续输入正确的数字。
本着虚心学习的态度,就想着怎么实现支付宝的这个效果比较好的卡号输入,本以为很简单,可以很快搞定,最后却用了大半天才实现了比较完美的效果。废话不多说,直接上代码:
/**
* UITextField Category 用于控制光标位置
*/
@interface UITextField (ExtendRange)
- (NSRange)selectedRange;
- (void)setSelectedRange:(NSRange)range;
@end
@implementation UITextField (ExtendRange)
- (NSRange)selectedRange {
UITextPosition *beginning = self.beginningOfDocument;
UITextRange *selectedRange = self.selectedTextRange;
UITextPosition *selectionStart = selectedRange.start;
UITextPosition *selectionEnd = selectedRange.end;
const NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
const NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
return NSMakeRange(location, length);
}
- (void)setSelectedRange:(NSRange)range {
UITextPosition *beginning = self.beginningOfDocument;
UITextPosition *startPosition = [self positionFromPosition:beginning offset:range.location];
UITextPosition *endPosition = [self positionFromPosition:beginning offset:range.location + range.length];
UITextRange *selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
[self setSelectedTextRange:selectionRange];
}
@end
//每组个数
static NSInteger const kGroupSize = 4;
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == self.bankCardNoField) {
NSString *text = textField.text;
NSString *beingString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *cardNo = [self removingSapceString:beingString];
//校验卡号只能是数字,且不能超过20位
if ( (string.length != 0 && ![self isValidNumbers:cardNo]) || cardNo.length > 20) {
return NO;
}
//获取【光标右侧的数字个数】
NSInteger rightNumberCount = [self removingSapceString:[text substringFromIndex:textField.selectedRange.location + textField.selectedRange.length]].length;
//输入长度大于4 需要对数字进行分组,每4个一组,用空格隔开
if (beingString.length > kGroupSize) {
textField.text = [self groupedString:beingString];
} else {
textField.text = beingString;
}
text = textField.text;
/**
* 计算光标位置(相对末尾)
* 光标右侧空格数 = 所有的空格数 - 光标左侧的空格数
* 光标位置 = 【光标右侧的数字个数】+ 光标右侧空格数
*/
NSInteger rightOffset = [self rightOffsetWithCardNoLength:cardNo.length rightNumberCount:rightNumberCount];
NSRange currentSelectedRange = NSMakeRange(text.length - rightOffset, 0);
//如果光标左侧是一个空格,则光标回退一格
if (currentSelectedRange.location > 0 && [[text substringWithRange:NSMakeRange(currentSelectedRange.location - 1, 1)] isEqualToString:@" "]) {
currentSelectedRange.location -= 1;
}
[textField setSelectedRange:currentSelectedRange];
return NO;
}
return YES;
}
#pragma mark - Helper
/**
* 计算光标相对末尾的位置偏移
*
* @param length 卡号的长度(不包括空格)
* @param rightNumberCount 光标右侧的数字个数
*
* @return 光标相对末尾的位置偏移
*/
- (NSInteger)rightOffsetWithCardNoLength:(NSInteger)length rightNumberCount:(NSInteger)rightNumberCount {
NSInteger totalGroupCount = [self groupCountWithLength:length];
NSInteger leftGroupCount = [self groupCountWithLength:length - rightNumberCount];
NSInteger totalWhiteSpace = totalGroupCount -1 > 0? totalGroupCount - 1 : 0;
NSInteger leftWhiteSpace = leftGroupCount -1 > 0? leftGroupCount - 1 : 0;
return rightNumberCount + (totalWhiteSpace - leftWhiteSpace);
}
/**
* 校验给定字符串是否是纯数字
*
* @param numberStr 字符串
*
* @return 字符串是否是纯数字
*/
- (BOOL)isValidNumbers:(NSString *)numberStr {
NSString* numberRegex = @"^[0-9]+$";
NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",numberRegex];
return [numberPre evaluateWithObject:numberStr];
}
/**
* 去除字符串中包含的空格
*
* @param str 字符串
*
* @return 去除空格后的字符串
*/
- (NSString *)removingSapceString:(NSString *)str {
return [str stringByReplacingOccurrencesOfString:@" " withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, str.length)];
}
/**
* 根据长度计算分组的个数
*
* @param length 长度
*
* @return 分组的个数
*/
- (NSInteger)groupCountWithLength:(NSInteger)length {
return (NSInteger)ceilf((CGFloat)length /kGroupSize);
}
/**
* 给定字符串根据指定的个数进行分组,每一组用空格分隔
*
* @param string 字符串
*
* @return 分组后的字符串
*/
- (NSString *)groupedString:(NSString *)string {
NSString *str = [self removingSapceString:string];
NSInteger groupCount = [self groupCountWithLength:str.length];
NSMutableArray *components = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < groupCount; i++) {
if (i*kGroupSize + kGroupSize > str.length) {
[components addObject:[str substringFromIndex:i*kGroupSize]];
} else {
[components addObject:[str substringWithRange:NSMakeRange(i*kGroupSize, kGroupSize)]];
}
}
NSString *groupedString = [components componentsJoinedByString:@" "];
return groupedString;
}