随手写了个,支持选择删除 可自己优化封装使用,有问题请评论
- (IBAction)textChange:(UITextField *)textField {
//去空
NSString * string = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
if (!string.length) {
textField.text = @"";
return;
}
if (string.length >= 11) {
string = [string substringToIndex:11];
}
NSNumber * number = [NSNumber numberWithInteger:[string integerValue]];
NSNumberFormatter * formatter = [NSNumberFormatter new];
//设置分隔符
[formatter setGroupingSeparator:@" "];
//设置使用组分割
formatter.usesGroupingSeparator = YES;
// 数字分割的尺寸<从右向左>
formatter.groupingSize = ([string length]-3)%4>0?([string length]-3)%4:4;
//除了groupingSize决定的尺寸外,其他数字位分割的尺寸
formatter.secondaryGroupingSize = [string length]>7?4:3;
//获取格式化后765的字符
textField.text = [formatter stringFromNumber:number];
if (position) {
textField.selectedTextRange = selrange;
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
selrange = textField.selectedTextRange;
NSInteger location = [textField offsetFromPosition:textField.beginningOfDocument toPosition:selrange.end];
NSLog(@"location =%zi",location);
NSInteger index;
if ([string isEqualToString:@""]) {
index = location%5?-1:-2;
} else {
index = (location-3)%5?1:2;
}
position = [textField positionFromPosition:selrange.start offset:index];
selrange = [textField textRangeFromPosition:position toPosition:position];
NSLog(@"%@,%@",position,selrange);
if (textField.text.length >= 13 && ![string isEqualToString:@""]) {
return NO;
}
return YES;
}