输入手机号 实现自动三 四 四格式

用的是空格,如果用- 把空格换成- 就OK

 

#define NUMBERS @"0123456789"

 1 //键盘改变,控制变更
 2 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {  3     
 4     NSCharacterSet*cs;  5     cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];  6     NSString*filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];  7     BOOL basicTest = [string isEqualToString:filtered];  8 
 9     NSInteger existedLength = textField.text.length; 10     NSInteger selectedLength = range.length; 11     NSInteger replaceLength = string.length; 12     
13     if (existedLength - selectedLength + replaceLength >14) { 14         return NO; 15  } 16 
17     
18     if(basicTest) 19  { 20         if (textField == phoneTxtField) 21  { 22 
23             if ([string isEqualToString:@""]){ // 删除字符
24                 if (((textField.text.length - 2) % 4 == 0) &&((textField.text.length - 2) % 6 != 0)) { 25                     textField.text = [textField.text substringToIndex:textField.text.length - 1]; 26                 }else if ((textField.text.length - 2) % 9 == 0){ 27                     textField.text = [textField.text substringToIndex:textField.text.length - 1]; 28  } 29                 return YES; 30             } else { 31                 if (textField.text.length<5) { 32                     if (textField.text.length % 4 == 0) { 33                         textField.text = [NSString stringWithFormat:@"%@ ", textField.text]; 34  } 35                 }else{ 36                     if (textField.text.length % 9 == 0) { 37                     textField.text = [NSString stringWithFormat:@"%@ ", textField.text]; 38  } 39  } 40                 
41  } 42             return YES; 43  } 44  } 45     else
46  { 47         return NO; 48  } 49     
50     
51     if (string.length == 0) { 52         
53         return YES; 54  } 55     
56     
57     return YES; 58     
59 
60     
61 } 62 
63 
64 //键盘关闭
65 -(void)textFieldDidEndEditing:(UITextField *)textField 66 { 67     if ((textField == phoneTxtField) &&(textField.text.length==14) ){ 68        NSLog(@"输入了九位");

       

 userPhone=[phoneTxtField.text stringByReplacingOccurrencesOfString:@" " withString:@""];

        NSLog(@"%@",userPhone);

 

 

82

83  } 84 }

 

你可能感兴趣的:(输入手机号 实现自动三 四 四格式)