如何在iOS中实时格式化电话号码(使用UITextfield时)以获取不同的区域代码?

时间:2015-02-04 06:49:52

标签: ios libphonenumber

我找到了' NBAsYouTypeFormatter ',并参考了所提供的演示。但是,当用户在UITextField中输入电话号码时,我想要动态格式化电话号码。

请注意,在我的情况下,区域代码不会固定到一个或两个国家/地区,例如只有@“US”或其他。用户从下拉列表中选择区域代码,选择的代码将由我通过以下行传递:

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

现在,当用户在数字文本字段中键入时,如何动态格式化数字文本字段?

2 个答案:

答案 0 :(得分:10)

以下是我如何实现这一目标。我将从头开始解释。因此,新用户可以从头开始。

here下载 libPhoneNumber-iOS 库。在该链接页面的底部,您将找到需要添加到项目中的文件。

您的捆绑包应如下所示:

Bundle

现在,按照以下步骤实施。

(1)在视图控制器中导入需要格式化文本字段的文件。

#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的委托方法中,动态管理yout textfield的文本。

#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;
}

希望它可以帮助别人!!!

答案 1 :(得分: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;
}

希望这个帮助