2012-07-09 158 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 

回答

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

} 

希望這有助於你:UITextFieldDelegate通過獲取UITextField的文本,並運行,我寫了一個小方法處理textField:shouldChangeCharactersInRange :replacementString:方法!

相關問題