如何将NSString格式化为美国的电话号码?

问题描述:

我有一个简单的应用程序,可以帮助招聘者在活动中收集信息。一个表单字段是用于输入电话号码的,我想用一种简单的方法在用户输入时重新设置电话号码的格式。如何将NSString格式化为美国的电话号码?

电话号码应随着用户类型,因此对于数字的字符串应该是这样的样本输出:

1 
1 (20) 
1 (206) 55 
1 (206) 555-55 
1 (206) 555-5555 

或者,如果用户未在区号前输入1 ,该电话号码将演变是这样的:

(20) 
(206) 55 
(206) 555-55 
(206) 555-5555 

如果电话号码太长,那么它应该只是显示号码的普通字符串:

20655555555555555 

这里就是我所做的:

-(void)updatePhoneNumberWithString:(NSString *)string { 

    NSMutableString *finalString = [NSMutableString new]; 
    NSMutableString *workingPhoneString = [NSMutableString stringWithString:string]; 

    if (workingPhoneString.length > 0) { 
    //This if statement prevents errors when the user deletes the last character in the textfield. 

     if ([[workingPhoneString substringToIndex:1] isEqualToString:@"1"]) { 
     //If the user typed a "1" as the first digit, then it's a prefix before the area code. 
      [finalString appendString:@"1 "]; 
      [workingPhoneString replaceCharactersInRange:NSMakeRange(0, 1) withString:@""]; 
     } 

     if (workingPhoneString.length < 3) { 
     //If the user is dialing the area code... 
      [finalString appendFormat:[NSString stringWithFormat:@"(%@)", workingPhoneString]]; 

     } else if (workingPhoneString.length < 6) { 
     //If the user is dialing the 3 digits after the area code... 
      [finalString appendFormat:[NSString stringWithFormat:@"(%@) %@", 
             [workingPhoneString substringWithRange:NSMakeRange(0, 3)], 
             [workingPhoneString substringFromIndex:3]]]; 

     } else if (workingPhoneString.length < 11) { 
     //If the user is dialing the last 4 digits of the phone number... 
      [finalString appendFormat:[NSString stringWithFormat:@"(%@) %@-%@", 
             [workingPhoneString substringWithRange:NSMakeRange(0, 3)], 
             [workingPhoneString substringWithRange:NSMakeRange(3, 3)], 
             [workingPhoneString substringFromIndex:6]]]; 
     } else { 
     //If the user's typed in a bunch of characters, then just show the full string. 
      finalString = phoneString; 
     } 

     phoneNumberField.text = finalString; 
    } else { 
    //If the user changed the textfield to contain no text at all... 
     phoneNumberField.text = @""; 
    } 

} 

希望这有助于你:UITextFieldDelegate通过获取UITextField的文本,并运行,我写了一个小方法处理textField:shouldChangeCharactersInRange :replacementString:方法!