ios - 如何在 iOS 中针对不同的区域代码实时格式化电话号码(使用 UITextfield 时)?

标签 ios libphonenumber

我找到了“NBAsYouTypeFormatter”并引用了提供的演示。但是,我希望当用户在 UITextField 中输入电话号码时动态格式化电话号码。

请记住,在我的案例中,区域代码并不固定为一个或两个国家,例如仅@“US”或仅其他。区域代码将由用户从下拉列表中选择,所选代码将由我通过以下行传递:

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

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

最佳答案

我是这样实现的。我将从头开始解释。因此,新用户可以从头开始。

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

你的包应该是这样的:

Bundle

现在,按照以下步骤进行实现。

(1) 在需要格式化文本字段的 View Controller 中导入文件。

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

并在头文件中生成 NBAsYouTypeFormatter 类型的实例:

NBAsYouTypeFormatter *asYouTypeFormatter;

(2) 在该 View Controller 的 viewDidLoad 方法中,初始化之前获取的对象:

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

注意:@"IN"代表印度。您可以将其设置为任何您想要的。请参阅将包含在 libPhoneNumber-iOS 库中的 plist 文件以查看区域代码的完整列表。

(3)在UITextField的delegate方法中,动态管理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;
}

希望对其他人有帮助!!!

关于ios - 如何在 iOS 中针对不同的区域代码实时格式化电话号码(使用 UITextfield 时)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28315146/

相关文章:

java - libphonenumber - 在不知道国家代码的情况下格式化电话号码

ios - AppleLanguages 不再返回所有语言

ios - 模块名称前缀应该已被 native 端剥离,但不适用于 RCTJSCExecutor

javascript - libphonenumber-js 将好的电话号码评估为 false

javascript - libphonenumber-js : 'Uncaught TypeError: A text for parsing must be a string'

android - 使用 PhoneNumberFormattingTextWatcher 无需输入国家代码

ios - 保留对 Core Data 对象的引用是否不好?

android - 如何检查设备上是否安装了 WhatsApp?

ios - 当我们在ios中选择最后一个按钮时如何选择所有按钮

javascript - libphonenumber [Js] 仅获取国家/地区代码