0

私は、リクルーターがイベント中に情報を収集するのに役立つシンプルなアプリを持っています。1つのフォームフィールドは電話番号用で、ユーザーが入力するときに電話番号を再フォーマットする簡単な方法が必要でした。

電話番号はユーザーの入力に応じて変化するため、一連の数字の出力例は次のようになります。

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
4

1 に答える 1

3

これが私がしたことです:UITextFieldDelegateハンドルはtextField:shouldChangeCharactersInRange :replacementString:、のテキストを取得し、UITextField私が書いた小さなメソッドを実行することによってメソッドを処理します:

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

}

これがお役に立てば幸いです。

于 2012-07-09T23:51:01.297 に答える