1.输入银行卡号,银行卡号以4位隔开,输到一定位数时,光标回到已输字符中间再次输入,银行卡位数,便不会成4位隔开了;
解决:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField) {
NSString* text = textField.text;
//删除
if([string isEqualToString:@""]){
//删除一位
if(range.length == 1){
//最后一位,遇到空格则多删除一次
if (range.location == text.length-1 ) {
if ([text characterAtIndex:text.length-1] == ' ') {
[textField deleteBackward];
}
return YES;
}
//从中间删除
else{
NSInteger offset = range.location;
if (range.location < text.length && [text characterAtIndex:range.location] == ' ' && [textField.selectedTextRange isEmpty]) {
[textField deleteBackward];
offset --;
}
[textField deleteBackward];
textField.text = [self parseString:textField.text];
UITextPosition *newPos = [textField positionFromPosition:textField.beginningOfDocument offset:offset];
textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];
return NO;
}
}
else if (range.length > 1) {
BOOL isLast = NO;
//如果是从最后一位开始
if(range.location + range.length == textField.text.length ){
isLast = YES;
}
[textField deleteBackward];
textField.text = [self parseString:textField.text];
NSInteger offset = range.location;
if (range.location == 4 || range.location == 9 ||range.location == 14 ||range.location == 19) {
offset ++;
}
if (isLast) {
//光标直接在最后一位了
}else{
UITextPosition *newPos = [textField positionFromPosition:textField.beginningOfDocument offset:offset];
textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];
}
return NO;
}
else{
return YES;
}
}
else if(string.length >0){
//限制输入字符个数,限制位数
if (([self noneSpaseString:textField.text].length + string.length - range.length > 19) ) {
return NO;
}
[textField insertText:string];
textField.text = [self parseString:textField.text];
NSInteger offset = range.location + string.length;
if (range.location == 4 || range.location == 9 ||range.location == 14 ||range.location == 19) {
offset ++;
}
UITextPosition *newPos = [textField positionFromPosition:textField.beginningOfDocument offset:offset];
textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];
return NO;
}else{
return YES;
}
}
return YES;
}
-(NSString*)noneSpaseString:(NSString*)string
{
return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}
- (NSString*)parseString:(NSString*)string
{
if (!string) {
return nil;
}
NSMutableString* mStr = [NSMutableString stringWithString:[string stringByReplacingOccurrencesOfString:@" " withString:@""]];
if (mStr.length >4) {
[mStr insertString:@" " atIndex:4];
}if (mStr.length > 9) {
[mStr insertString:@" " atIndex:9];
}
if (mStr.length >14) {
[mStr insertString:@" " atIndex:14];
}
if (mStr.length >19) {
[mStr insertString:@" " atIndex:19];
}
return mStr;
}