电话号码格式ios [英] Phone number format ios

查看:156
本文介绍了电话号码格式ios的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我将电话号码作为用户的输入。号码应采用美国格式。我想动态地显示它像(555)-888-888。例如,当用户在达到4位时开始输入数字时,它显示如下的数字(555)-4,依此类推。我尝试使用replaceString方法,但我发现它不起作用。

In my app I am taking phone number as an input from user. Number should be in US format. I want to display it like (555)-888-888 dynamically. For example when user starts to input number when he reaches to 4 digit it shows number like this (555)-4 and so on. I tried to replaceString method but i found that it will not work.

推荐答案

我将从头开始解释。因此,新用户可以从头开始。

I am going to explain from scratch. So, new users can get the way from start.

libPhoneNumber-iOS 库。 com / iziz / libPhoneNumber-iOSrel =nofollow>这里。在该链接页面的底部,您将找到需要添加到项目中的文件。

Download libPhoneNumber-iOS library from here. At the bottom side of the page of that link, you will find what files you need to add to your project.

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

Now, follow below steps to implement.

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

(1) Import files in the view controller where you need your textfield to be formatted.

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

并在头文件中创建 NBAsYouTypeFormatter 类型的实例:

and make instance of type NBAsYouTypeFormatter in header file:

NBAsYouTypeFormatter *asYouTypeFormatter;

(2) viewDidLoad 该视图控制器的方法,初始化之前采用的对象:

(2) In the viewDidLoad method of that view controller, initialize that object taken earlier:

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

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

Note: @"IN" is for India. You can set it to anything you want. Refer to plist file that will be included in libPhoneNumber-iOS library to view full list of region codes.

(3)在委托方法中 UITextField ,动态管理yout textfield的文本。

(3) In delegate method of UITextField, dynamically manage text of 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)
        {
            [txtNumber setText:[asYouTypeFormatter inputDigit:string]];
        }

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

    return NO;
}

希望有所帮助!!!

这篇关于电话号码格式ios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆