2012-07-09 2 views
0

이벤트가 진행되는 동안 채용 담당자가 정보를 수집하는 데 도움이되는 간단한 앱이 있습니다. 하나의 양식 필드는 전화 번호 용이었으며 사용자 유형에 따라 전화 번호를 다시 형식화하는 간단한 방법이 필요했습니다.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 
,691,363을 (210)

답변

3

는 여기에 내가했던 일이야 : 이것은 당신을 도와줍니다

-(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 = @""; 
    } 

} 

희망을 다음 UITextFieldDelegateUITextField의 텍스트를 받고, 그리고 내가 쓴 약간의 방법을 실행하여 textField:shouldChangeCharactersInRange :replacementString: 방법을 처리합니다!

관련 문제