5

「 NBAsYouTypeFormatter 」を見つけ、提供されたデモを参照しました。しかし、ユーザーが UITextField に電話番号を入力するときに、電話番号を動的にフォーマットする必要があります。

私の場合、地域コードは 1 つまたは 2 つの国に固定されていないことを思い出してください。たとえば、@"US" のみ、またはその他のみです。地域コードはユーザーがドロップダウンから選択し、選択したコードは次の行で渡されます。

NBAsYouTypeFormatter *asYouTypeFormatter = [[NBAsYouTypeFormatter alloc] initWithRegionCode:@"US"];  // may be any other than 'US'
NSString *output = [asYouTypeFormatter inputString:@"9999988888"];

さて、ユーザーが数値テキストフィールドに入力したときに数値テキストフィールドを動的にフォーマットするにはどうすればよいでしょうか?

4

2 に答える 2

10

これが私がそれを達成した方法です。一から説明していきます。したがって、新しいユーザーは最初から道を譲ることができます。

ここからlibPhoneNumber-iOSライブラリをダウンロードします。そのリンクのページの下部に、プロジェクトに追加する必要があるファイルが表示されます。

バンドルは次のようになります。

バンドル

それでは、以下の手順に従って実装してください。

(1)テキストフィールドをフォーマットする必要があるView Controllerにファイルをインポートします。

#import "NBPhoneMetaDataGenerator.h"
#import "NBPhoneNumberUtil.h"
#import "NBAsYouTypeFormatter.h"

ヘッダー ファイルにタイプNBAsYouTypeFormatterのインスタンスを作成します。

NBAsYouTypeFormatter *asYouTypeFormatter;

(2)そのビュー コントローラのviewDidLoadメソッドで、以前に取得したオブジェクトを初期化します。

asYouTypeFormatter = [[NBAsYouTypeFormatter alloc] initWithRegionCode:@"IN"];

注: @"IN" はインドを表します。好きなように設定できます。地域コードの完全なリストを表示するには、libPhoneNumber-iOS ライブラリに含まれる plist ファイルを参照してください。

(3) UITextField のデリゲート メソッドで、テキスト フィールドのテキストを動的に管理します。

#pragma mark
#pragma mark - Phone Number textfield formatting

# define LIMIT 18 // Or whatever you want

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // Just allow 18 digits
    if(!(([string length] + range.location) > LIMIT))
    {
        // Something entered by user
        if(range.length == 0)
        {
            [textNumber setText:[self.asYouTypeFormatter inputDigit:string]];
        }

        // Backspace
        else if(range.length == 1)
        {
            [textNumber setText:[self.asYouTypeFormatter removeLastDigit]];
        }
    }

    return NO;
}

それが他の人に役立つことを願っています!!!

于 2015-02-04T12:17:32.447 に答える
5

UITextFieldデリゲートのメソッド内

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *totalString = [NSString stringWithFormat:@"%@%@",textField.text,string];

    if (range.length == 1)
    {
        // Delete button was hit.. so tell the method to delete the last char.
        NSError *error = nil;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\\s-\\(\\)]" options:NSRegularExpressionCaseInsensitive error:&error];
        totalString = [regex stringByReplacingMatchesInString:totalString options:0 range:NSMakeRange(0, [totalString length]) withTemplate:@""];
        totalString = [totalString substringToIndex:[totalString length] - 1];
    }

    textField.text = [Utility formatPhoneNumber:totalString countryCode:@"theCountryCode"];

    return NO;
}

この関数は、指定された国コードに基づいて、文字列を電話形式の番号にフォーマットします。

+ (NSString *)formatPhoneNumber:(NSString *)simpleNumber countryCode:(NSString *)countryCode
{
    if (simpleNumber.length == 0)
    {
        return @"";
    }

    NSInteger maxLen = 15;

    // use regex to remove non-digits(including spaces) so we are left with just the numbers
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^[0-9+]]" options:NSRegularExpressionCaseInsensitive error:&error];
    simpleNumber = [regex stringByReplacingMatchesInString:simpleNumber options:0 range:NSMakeRange(0, [simpleNumber length]) withTemplate:@""];

    // check if the number is to long
    if (simpleNumber.length > maxLen)
    {
        // remove last extra chars.
        simpleNumber = [simpleNumber substringToIndex:maxLen];
    }

    NSString *firstChar = @"";
    BOOL countryCodeLen = countryCode.length;

    if (simpleNumber.length > 0)
    {
        firstChar = [simpleNumber substringToIndex:1];
    }

    if ([firstChar isEqualToString:@"+"])
    {
        //+1 (234)
        if (simpleNumber.length < 5 + countryCodeLen)
        {
            NSString *string = [NSString stringWithFormat:@"(\\d{%d})(\\d+)",countryCodeLen];
            //            simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\\d{1})(\\d+)"
            simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:string
                                                                   withString:@"$1 ($2)"
                                                                      options:NSRegularExpressionSearch
                                                                        range:NSMakeRange(0, [simpleNumber length])];
        }
        //+1 (234) 567
        else if(simpleNumber.length < 8 + countryCodeLen)
        {
            NSString *string = [NSString stringWithFormat:@"(\\d{%d})(\\d{3})(\\d+)",countryCodeLen];
            //            simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\\d{1})(\\d{3})(\\d+)"
            simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:string
                                                                   withString:@"$1 ($2) $3"
                                                                      options:NSRegularExpressionSearch
                                                                        range:NSMakeRange(0, [simpleNumber length])];
        }
        //+1 (234) 567-
        else   // else do this one..
        {
            NSString *string = [NSString stringWithFormat:@"(\\d{%d})(\\d{3})(\\d{3})(\\d+)",countryCodeLen];
            //            simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\\d{1})(\\d{3})(\\d{3})(\\d+)"
            simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:string
                                                                   withString:@"$1 ($2) $3-$4"
                                                                      options:NSRegularExpressionSearch
                                                                        range:NSMakeRange(0, [simpleNumber length])];
        }
    }
    else
    {
        // 123 456 7890
        // format the number.. if it's less then 7 digits.. then use this regex.
        if (simpleNumber.length < 7)
        {
            simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\\d{3})(\\d+)"
                                                                   withString:@"($1) $2"
                                                                      options:NSRegularExpressionSearch
                                                                        range:NSMakeRange(0, [simpleNumber length])];
        }
        else   // else do this one..
        {
            simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\\d{3})(\\d{3})(\\d+)"
                                                                   withString:@"($1) $2-$3"
                                                                      options:NSRegularExpressionSearch
                                                                        range:NSMakeRange(0, [simpleNumber length])];
        }
    }

    return simpleNumber;
}

この助けを願っています

于 2015-02-04T07:31:36.283 に答える