- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
BOOL returnValue = YES;
NSMutableString* newText = [NSMutableString stringWithCapacity:0];
[newText appendString:textField.text];// 拿到原有text,根据下面判断可能给它添加" "(空格);
NSString * noBlankStr = [textField.text stringByReplacingOccurrencesOfString:@" "withString:@""];
NSInteger textLength = [noBlankStr length];
if (string.length) {
if (textLength < 25) {//这个25是控制实际字符串长度,比如银行卡号长度
if (textLength > 0 && textLength %4 == 0 ) {
newText = [NSMutableString stringWithString:[newText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
[newText appendString:@" "];
[newText appendString:string];
textField.text = newText;
returnValue = NO;//为什么return NO?因为textField.text = newText;text已经被我们替换好了,那么就不需要系统帮我们添加了,如果你ruturnYES的话,你会发现会多出一个字符串
}else {
[newText appendString:string];
}
}else { // 比25长的话 return NO这样输入就无效了
returnValue =NO;
}
}else { // 如果输入为空,该怎么地怎么地
[newText replaceCharactersInRange:range withString:string];
}
return returnValue;
}
银行卡去空格:
首先添加一个target方法
[self.tf addTarget:self action:@selector(tfValueChange:) forControlEvents:UIControlEventEditingChanged];
- (void)tfValueChange:(id)sender {
// NSString *str = [self.tf.text substringFromIndex:self.tf.text.length-2];
if(self.tf.text.length<=4){
return;
}
NSString *str = [self.tf.text substringFromIndex:self.tf.text.length-1];
NSLog(@"%@",str);
if([str isEqualToString:@" "] && str.length%4==1){
NSMutableString* newText = [NSMutableString stringWithCapacity:0];
[newText appendString:self.tf.text];// 拿到原有text,根据下面判断可能给它添加" "(空格);
NSRange range = NSMakeRange(self.tf.text.length-1,1);
[newText deleteCharactersInRange:range];
self.tf.text =newText;
NSLog(@"=======%@",newText);
}
}