我找到了“NBAsYouTypeFormatter”并引用了提供的演示。但是,我希望当用户在 UITextField 中输入电话号码时动态格式化电话号码。
请记住,在我的案例中,区域代码并不固定为一个或两个国家,例如仅@“US”或仅其他。区域代码将由用户从下拉列表中选择,所选代码将由我通过以下行传递:
NBAsYouTypeFormatter *asYouTypeFormatter = [[NBAsYouTypeFormatter alloc] initWithRegionCode:@"US"]; // may be any other than 'US'
NSString *output = [asYouTypeFormatter inputString:@"9999988888"];
现在,当用户在数字文本字段中键入时,我如何能够动态地格式化数字文本字段?
最佳答案
我是这样实现的。我将从头开始解释。因此,新用户可以从头开始。
从here下载libPhoneNumber-iOS库.在该链接页面的底部,您将找到需要添加到项目中的文件。
你的包应该是这样的:
现在,按照以下步骤进行实现。
(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/