2022-01-27

iOS UITextField输入框实现输入手机号时自动添加空格

前景:需求很简单,输入框手机号自动加空格,度娘方法一大堆,但是都有bug啊,要么空格不能删除,要么光标输入错位,总之,一言难尽,公司之前的一个小伙伴写了一堆逻辑,但是也不能解决所有的问题,不完美,测试测出来被告知,“要加空格就是这样,我解决不了”,当时我也没在意。以为影响不到,直到最近,这个问题被无限放大了,问题是:把光标移动到中间输入一个后,光标就会跳到最后的位置,这样导致用户输入的手机号就不对,然后就去改,改了又改,永远输不对,这玩个屁,直接卸载了...
好了,不啰嗦了,直接上代码!

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
   NSString *text = [textField text];
   NSInteger init = text.length; // 初始
   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:@""];
   // 如果是电话号码格式化,需要添加这三行代码
   NSMutableString *temString = [NSMutableString stringWithString:text];
   [temString insertString:@" " atIndex:0];
   text = temString;
   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]];
   NSInteger num = newString.length-init; // 增加的位数
   if (num < 0) {
       num = 1;
   }
   if (newString.length >= 14) {
       return NO;
   }
   [textField setText:newString];
   self.loginButton.enabled = newString.length == 13; // 按钮的点击状态
   // 删除操作
   if (range.length == 1 && string.length == 0) {
       [self cursorLocation:textField index:range.location];
   }else {
       [self cursorLocation:textField index:range.location+num];
   }
   return NO;
}

// 改变光标位置
- (void)cursorLocation:(UITextField*)textField index:(NSInteger)index {
   NSInteger length = textField.text.length;
   if (length

你可能感兴趣的:(2022-01-27)